【问题标题】:How to erase line from text file in Python?如何从 Python 中的文本文件中删除行?
【发布时间】:2016-04-22 05:45:00
【问题描述】:

我正在尝试编写代码来重写 .txt 文件中的特定行。 我可以在我想要的行中写,但我不能删除行上的前一个文本。

这是我的代码:
(我正在尝试几件事)

def writeline(file,n_line, text):
    f=open(file,'r+')
    count=0
    for line in f:
        count=count+1
        if count==n_line :
            f.write(line.replace(str(line),text))
            #f.write('\r'+text)

您可以使用此代码制作测试文件进行测试:

with open('writetest.txt','w') as f:
    f.write('1 \n2 \n3 \n4 \n5')

writeline('writetest.txt',4,'This is the fourth line')

编辑:出于某种原因,如果我使用 'if count==5:' 代码编译正常(即使它没有删除以前的文本),但如果我使用 'if count==n_line:',该文件以大量垃圾告终。

答案有效,但我想知道我的代码有什么问题,以及为什么我不能读写。谢谢!

【问题讨论】:

    标签: python io


    【解决方案1】:

    您正在读取文件并写入文件。不要那样做。相反,您应该写到NamedTemporaryFile 然后rename 在您完成写入并关闭它后覆盖原始文件。

    或者如果保证文件大小很小,可以使用readlines()读取全部,然后关闭文件,修改你想要的行,然后写回:

    def editline(file,n_line,text):
        with open(file) as infile:
            lines = infile.readlines()
        lines[n_line] = text+' \n'
        with open(file, 'w') as outfile:
            outfile.writelines(lines)
    

    【讨论】:

      【解决方案2】:

      使用临时文件:

      import os
      import shutil
      
      
      def writeline(filename, n_line, text):
          tmp_filename = filename + ".tmp"
      
          count = 0
          with open(tmp_filename, 'wt') as tmp:
              with open(filename, 'rt') as src:
                  for line in src:
                      count += 1
                      if count == n_line:
                          line = line.replace(str(line), text + '\n')
                      tmp.write(line)
          shutil.copy(tmp_filename, filename)
          os.remove(tmp_filename)
      
      
      def create_test(fname):
          with open(fname,'w') as f:
              f.write('1 \n2 \n3 \n4 \n5')
      
      if __name__ == "__main__":
          create_test('writetest.txt')
          writeline('writetest.txt', 4, 'This is the fourth line')
      

      【讨论】:

        猜你喜欢
        • 2020-03-05
        • 2023-02-08
        • 2018-09-21
        • 1970-01-01
        • 2013-08-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-12
        相关资源
        最近更新 更多