如何使用python从文本文件中删除特定行

时间:2016-11-01 22:26:55

标签: python

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

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

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

3 个答案:

答案 0 :(得分:2)

您可以使用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())

答案 1 :(得分:1)

您可以在不将整个文件加载到内存中的情况下执行此操作:

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)

答案 2 :(得分:1)

您可以简单地遍历整个文件并写入除要删除的行之外的所有行。使用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)