0

假设我有一个文件列表,我想遍历它,每个文件都读取它的内容,将内容发送到一个函数processContent(),然后将整个内容写回文件中。下面的代码是一种合适的方法吗?

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

换句话说,在同一个迭代中读取和写入。

4

1 回答 1

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

于 2013-05-28T21:06:54.407 回答