从文件中读取后写回同一文件

mis*_*ded 8 python io file python-2.6

我的目标是从文件中读取行,删除它末尾的空格并写回同一个文件.我试过以下代码:

with open(filename, 'r+') as f:
    for i in f:
        f.write(i.rstrip()+"\n")
Run Code Online (Sandbox Code Playgroud)

这似乎写在文件的末尾,保持文件中的初始数据不变.我知道使用f.seek(0)将指针返回到文件的开头,我假设这个解决方案需要某种方式.

你能否告诉我是否有不同的方法,或者我是否在正确的补丁上只需要在代码中添加更多逻辑?

Jon*_*yRo 6

使用临时文件.Python提供了以安全方式创建临时文件的工具.下面调用示例:python modify.py target_filename

 import tempfile
 import sys

 def modify_file(filename):

      #Create temporary file read/write
      t = tempfile.NamedTemporaryFile(mode="r+")

      #Open input file read-only
      i = open(filename, 'r')

      #Copy input file to temporary file, modifying as we go
      for line in i:
           t.write(line.rstrip()+"\n")

      i.close() #Close input file

      t.seek(0) #Rewind temporary file to beginning

      o = open(filename, "w")  #Reopen input file writable

      #Overwriting original file with temporary file contents          
      for line in t:
           o.write(line)  

      t.close() #Close temporary file, will cause it to be deleted

 if __name__ == "__main__":
      modify_file(sys.argv[1])
Run Code Online (Sandbox Code Playgroud)

参考文献:http: //docs.python.org/2/library/tempfile.html