我正在研究如何在Python中进行文件输入和输出。我编写了以下代码,从一个文件读取一个名称列表(每行一个)到另一个文件,同时根据文件中的名称检查一个名称,并将文本追加到文件中出现的名称。代码可以工作。还能做得更好吗?
我想对输入和输出文件都使用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')