Reputation: 4329
Suppose I have a list of files, and I want to iterate over it, for each one reading its content, sending the content to a function processContent()
, and writing the whole thing back into the file. Would the following code be an appropriate way to do it?
for curfile in files:
with open(curfile, 'r+') as infile
content = infile.read()
processed_content = processContent(content)
infile.write(processed_content)
In other words, reading and writing in the same iteration.
Upvotes: 0
Views: 215
Reputation: 250951
for curfile in files:
with open(curfile, 'r+') as infile:
content = infile.read()
processed_content = processContent(content)
infile.truncate(0) # truncate the file to 0 bytes
infile.seek(0) # move the pointer to the start of the file
infile.write(processed_content)
Or use a temporary file to write the new content and then rename it back to the original file:
import os
for curfile in files:
with open(curfile) as infile:
with open("temp_file", 'w') as outfile:
content = infile.read()
processed_content = processContent(content)
outfile.write(processed_content)
os.remove(curfile) # For windows only
os.rename("temp_file", curfile)
If you want to process one line at once then try fileinput
module
Upvotes: 4