假设我有一个文件列表,我想迭代它,为每个读取其内容,将内容发送到函数processContent()
,并将整个内容写回文件。以下代码是否适合这样做?
for curfile in files:
with open(curfile, 'r+') as infile
content = infile.read()
processed_content = processContent(content)
infile.write(processed_content)
换句话说,在同一次迭代中读写。
答案 0 :(得分:4)
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)
或使用临时文件编写新内容,然后将其重命名为原始文件:
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)
如果您想一次处理一行,请尝试fileinput
模块