我在爲我的python類編寫這個簡短程序時遇到了麻煩,我希望有人能提供一些幫助。Python - 讀寫用戶輸入
我想實現什麼: 1.編寫一個使用while循環接受用戶輸入的程序(如果用戶按Enter鍵,則退出程序)。 2.將輸入保存到文件,然後打印。 3.開始時,程序將顯示文件的當前內容。
實施例:
首次啓動程序。
輸入文本:這是輸入
此輸入。
輸入文本:其他文字
這是輸入。一些更多的文字。
當您啓動程序的第二次
此輸入。一些更多的文字。
輸入文本:
等等,等等
我有什麼至今:
intext = open('user_input.txt','a')
intext.close()
string_input = input('Enter text: ')
while True:
open_input = open('user_input.txt','r')
if open_input:
for i in open_input:
print(i)
if string_input != "":
uinput = open('user_input.txt','a')
uinput.write(string_input + '.')
uinput.close()
rd = open('user_input.txt', 'r')
if rd:
for line in rd:
print(line)
if string_input == "":
t = open('user_input.txt', 'r')
for line in t:
print(line)
t.close()
break
問題:一旦打開,所有先前存儲的文本不顯示。如果用戶輸入的文本以無限循環打印,並且不提示再次輸入文本。
肯定:輸入被記錄到文本文件。如果沒有輸入文字,退出之前輸入的文字會顯示正確。
就像我說的,這是我的作業。我已經尋找答案,但我似乎將代碼分開,並將其重新組合在一起,以獲得不同的錯誤。所以一些指導將不勝感激。
有一件事我忘了提的是,我使用的Python 3
再次
感謝David幫我覺得更像是一個程序員。結果如下:
intext = open('user_input.txt','r').readline()
print(intext)
while True:
string_input = input('Enter text: ')
if string_input == "":
t = open('user_input.txt', 'r').readline()
print(t)
break
if string_input != "":
d = open('user_input.txt', 'a')
d.write(string_input + '. ')
d.close()
n = open('user_input.txt', 'r').readline()
print(n)
我試着讓代碼儘可能的小,並且它現在可以工作。
我是否需要關閉該文件結尾:說出來的這個
一對夫婦的問題,其他問題?當我試圖關閉
apnd
和n
時,它給了我錯誤。在尋找答案時,我來到了一個對面,this。使用「with」語句是否仍然是最佳做法?
實施例:
with open("x.txt") as f:
data = f.read()
do something with data
感謝您的誠實。我會採取更有組織的方法回退一步。 – glw