python - 从文件读取后写回同一个文件

标签 python file io python-2.6

我的目标是从文件中读取行,去掉行尾的空格,然后写回同一个文件。我尝试了以下代码:

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

这似乎写在文件的末尾,保持文件中的初始数据完好无损。我知道使用 f.seek(0) 会将指针带回文件的开头,我假设此解决方案以某种方式需要它。

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

最佳答案

使用临时文件。 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])

引用资料: http://docs.python.org/2/library/tempfile.html

关于python - 从文件读取后写回同一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17646680/

相关文章:

c - C 中的 read() 错误

linux - ioread32 后跟 iowrite32 没有给出相同的值

python - 尽管有特定 View ,Django URL 冲突

python - 使用 pytesseract 时如何设置配置 load_system_dawg 以改善结果?

sql - Mysql:如何从其他sql脚本文件中调用sql脚本文件?

windows - 合并大量文件,仅包括部分文件名

python - 在python中使用变量创建txt文件

python - 如何找到 python 的 string.format(**kwargs) 失败的地方?

python - 如何使用 Factory Boy 和 Flask-SQLAlchemy 设置依赖工厂?

java - 什么情况下关闭流会失败?