I'm researching file input and output in Python. I wrote the code below to read a list of names (one per line) from one file into another, while checking a name against the names in the file and appending text to the occurrences in the file. The code is functional. Is it possible to do it better?
I'd like to use the with open(... statement for both input and output files, but I don't see how they could be in the same block, therefore I'd have to save the names somewhere temporary.
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:
line = line[0:len(txt)] + ' - Truly a great person!\n'
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')