我正在研究如何在Python中執行文件輸入和輸出。我寫了下面的代碼,從一個文件讀取一個名稱列表(每行一個)到另一個文件中,同時檢查文件中名稱的名稱並將文本附加到文件中的出現位置。代碼起作用。它能做得更好嗎?如何使用open語句打開文件
我想爲輸入和輸出文件使用with open(...
語句,但看不到它們可能在同一個塊中,這意味着我需要將名稱存儲在臨時位置。
def filter(txt, oldfile, newfile):
'''\
Read a list of names from a file line by line into an output file.
If a line begins with a particular name, insert a string of text
after the name before appending the line to the output file.
'''
outfile = open(newfile, 'w')
with open(oldfile, 'r', encoding='utf-8') as infile:
for line in infile:
if line.startswith(txt):
line = line[0:len(txt)] + ' - Truly a great person!\n'
outfile.write(line)
outfile.close()
return # Do I gain anything by including this?
# input the name you want to check against
text = input('Please enter the name of a great person: ')
letsgo = filter(text,'Spanish', 'Spanish2')
「這意味着我需要將名稱存儲在臨時位置」?你能解釋一下你的意思嗎? – 2012-02-14 19:58:50
請注意,filter()是[內建函數](https://docs.python.org/2/library/functions.html#filter),因此您應該爲函數選擇不同的名稱。 – Tom 2017-05-05 19:53:39
@Tom在命名空間中的函數是否覆蓋了內置函數? – UpTide 2017-11-08 19:59:35