【问题标题】:Appending characters to each line in a txt file with python使用python将字符附加到txt文件中的每一行
【发布时间】:2018-04-26 20:29:48
【问题描述】:

我编写了以下 python 代码 sn-p 来在 txt 文件的每一行附加一个低 p 字符:

f = open('helloworld.txt','r')
for line in f:
    line+='p'
print(f.read())
f.close()

但是,当我执行这个 python 程序时,它只返回一个空白:

zhiwei@zhiwei-Lenovo-Rescuer-15ISK:~/Documents/1001/ass5$ python3 helloworld.py

谁能告诉我我的代码有什么问题?

【问题讨论】:

  • 您是想简单地将其打印到您的终端,并在每行末尾添加额外的 p,还是在运行后修改文件版本?
  • @grovina 我想要修改版本的文件

标签: python python-2.7 python-3.x python-3.5


【解决方案1】:

目前,您只读取每一行而不写入文件。以写入模式重新打开文件并将完整的字符串写入其中,如下所示:

newf=""
with open('helloworld.txt','r') as f:
    for line in f:
        newf+=line.strip()+"p\n"
    f.close()
with open('helloworld.txt','w') as f:
    f.write(newf)
    f.close()

【讨论】:

    【解决方案2】:

    好吧,在 shell 中输入 help(f),你可以得到“BufferedIOBase 对象上的基于字符和行的层,缓冲区。” 意思是:如果你读第一个缓冲区,你可以得到内容,但又一次。它是空的。 像这样:

    with open(oldfile, 'r') as f1, open(newfile, 'w') as f2:
           newline = ''
           for line in f1:
             newline+=line.strip()+"p\n"
             f2.write(newline)   
    

    【讨论】:

      【解决方案3】:

      open(filePath, openMode) 有两个参数,第一个是文件的路径,第二个是打开它的模式。当您使用 'r' 作为第二个参数时,您实际上是在告诉 Python 将其作为只读文件打开。

      如果你想在上面写,你需要以写模式打开它,使用'w'作为第二个参数。您可以在其official documentation 中找到有关如何在 Python 中读取/写入文件的更多信息。

      如果你想同时读写,你必须以读写模式打开文件。您只需使用'r+' 模式即可做到这一点。

      【讨论】:

      • 我将 r 更改为 w,结果如下:IOError: File not open for reading
      【解决方案4】:

      看来你的for循环已经把文件读到最后了,所以f.read()返回空字符串。

      如果您只需要打印文件中的行,您可以像print(line) 一样将打印移动到 for 循环中。最好将 f.read() 移到 for 循环之前:

      f = open("filename", "r")
      lines = f.readlines()
      for line in lines:
          line += "p"
          print(line)
      f.close()
      

      如果需要修改文件,需要创建另一个文件obj并以“w”模式打开,并使用f.write(line)将修改后的行写入新文件中。

      另外,在python中用with子句代替open()更好,更pythonic。

      with open("filename", "r") as f:
          lines = f.readlines()
          for line in lines:
              line += "p"
              print(line)
      

      使用with子句时,不需要关闭文件,这样更简单。

      【讨论】:

      猜你喜欢
      • 2021-09-04
      • 2015-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-16
      • 1970-01-01
      相关资源
      最近更新 更多