在同一次迭代中读取和写入文件

时间:2013-05-28 21:01:15

标签: python file python-2.6

假设我有一个文件列表,我想迭代它,为每个读取其内容,将内容发送到函数processContent(),并将整个内容写回文件。以下代码是否适合这样做?

for curfile in files:
    with open(curfile, 'r+') as infile
        content = infile.read()
        processed_content = processContent(content)
        infile.write(processed_content)

换句话说,在同一次迭代中读写。

1 个答案:

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