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
模块