【问题标题】:In python, how can you delete the third forth and fifth line of a text file?在python中,如何删除文本文件的第三第四和第五行?
【发布时间】:2013-07-24 04:28:06
【问题描述】:

还有一个关于删除前三行和最后一行的问题,他们使用.writelines(),但只有在你想删除外面的行时才有效,而不是删除中间的行。

有什么方法可以从 python 中的文本文件中的任何位置删除多个特定行?

请,请,请帮助!!

【问题讨论】:

    标签: python file text lines


    【解决方案1】:

    试试下面的代码:

    with open('input.txt') as f, open('output.txt', 'w') as fout:
        fout.writelines(line for lineno, line in 
                            enumerate(f, 1) if lineno not in (3,4,5))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-06
      • 2013-12-20
      • 2013-08-27
      • 2022-10-01
      • 2012-06-01
      • 1970-01-01
      • 2021-06-01
      • 1970-01-01
      相关资源
      最近更新 更多