1

How can i remove a specific line from a text file using python. This is my code

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

  with open("Names.txt","w")
Tom
  • 43
  • 1
  • 13

3 Answers3

2

You can use itertools.islice to read the first N lines and trim from there. islice works much like a list slice (e.g., mylist[0:N:1]) but on any type of iterator such as a file object.

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())
tdelaney
  • 73,364
  • 6
  • 83
  • 116
2

You could simply iterate over the whole file and write all lines except the one you want to remove. Use enumerate to count the lines.

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)
Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
1

You can do it without loading the whole file in memory:

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)
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125