【问题标题】:How to remove a specific line from a text file with python [duplicate]如何使用python从文本文件中删除特定行[重复]
【发布时间】:2016-11-01 22:26:55
【问题描述】:

如何使用 python 从文本文件中删除特定行。这是我的代码

def Delete():
  num=int(input("Enter the line number you would like to delete: "))
  Del=num-1

  with open("Names.txt","w")

【问题讨论】:

  • 您可以将文件内容复制到一个变量,除了要删除的行,然后重新创建文件。 :)
  • 注意,有人可以输入非整数值...

标签: python


【解决方案1】:

您可以使用itertools.islice 读取前 N 行并从那里修剪。 islice 的工作方式很像列表切片(例如,mylist[0:N:1]),但适用于任何类型的迭代器,例如文件对象。

import os
import itertools

# create test file
with open('test.txt', 'w') as fp:
    fp.writelines('{}\n'.format(i) for i in range(1,11))

# invent some input
del_line = int('4')

# now do the work
with open('test.txt') as infp, open('newtest.txt', 'w') as outfp:
    outfp.writelines(itertools.islice(infp, 0, del_line-1, 1))
    next(infp)
    outfp.writelines(infp)
os.rename('newtest.txt', 'test.txt')

# see what we got
print(open('test.txt').read())

【讨论】:

    【解决方案2】:

    您可以简单地遍历整个文件并写入除要删除的行之外的所有行。使用enumerate 计算行数。

    badline = int(input('which line do you want to delete?'))
    
    with open('fordel.txt') as f, open('out.txt', 'w') as fo:
        for linenum, line in enumerate(f, start=1):
            if linenum != badline:
                fo.write(line)
    

    【讨论】:

      【解决方案3】:

      您可以在不将整个文件加载到内存中的情况下做到这一点:

      with open('input.txt', 'r') as f, open('output.txt', 'w') as g:
          current=0
          for line in f:
              if current==deleted:
                  break
              g.write(line)
              current=current+1
      
          for line in f:
              g.write(line)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-24
        • 2020-03-05
        • 2021-03-11
        • 2018-07-27
        • 1970-01-01
        • 2022-12-13
        • 2017-03-12
        • 1970-01-01
        相关资源
        最近更新 更多