Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (47.6k points)

I'm looking at how to do file input and output in Python. I've written the following code to read a list of names (one per line) from a file into another file while checking a name against the names in the file and appending text to the occurrences in the file. The code works. Could it be done better?

I'd wanted to use the with open(... statement for both input and output files but can't see how they could be in the same block meaning I'd need to store the names in a temporary location.

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' 



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')

1 Answer

0 votes
by (106k points)

You can use nested blocks like this:-

with open(newfile, 'w') as outfile: 

with open(oldfile, 'r', encoding='utf-8') as infile: 

# your logic goes right here

To know more about this you can have a look at the following video tutorial:-

Related questions

0 votes
1 answer
0 votes
1 answer
asked Sep 25, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

30.5k questions

32.5k answers


108k users

Browse Categories