2013-05-28 54 views
0

假设我有一个文件列表,我想遍历它,为每个文件读取它的内容,将内容发送到一个函数processContent(),然后将所有内容写回到文件。下面的代码是否是一个适当的方法来做到这一点?在同一迭代中读取和写入文件

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

换句话说,在相同的迭代中读写。

+1

我相信在写入之前你会想'infile.seek(0)'...真的应该只使用2个句柄... –

+2

我更喜欢使用临时文件,然后将其重命名为原始文件名。 –

+0

@StevenRumbalski我看到你在说什么,但是它会导致一个问题,因为我也在迭代文件? –

回答

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

+0

这有效,但它让我感到不舒服。截断和寻找的东西感觉有点过低。 –

+0

@ F3AR3DLEGEND问题标签为py2.6 –

+0

@AshwiniChaudhary啊,没有看到。 –