Deleting a line from a text file
Asked Answered
C

2

0

How to you delete a specific line from a text file using readlines()

like:

f_open = open("textfile.txt", "r")
lines = f_open.readlines()

How do you use lines to choose a line in textfile.txt and delete it?

Sorry if it doesn't make sense.

Curvature answered 18/5, 2013 at 11:8 Comment(1)
Does this answer your question? How to delete a specific line in a file?Frump
U
7

Use the fileinput module's inplace functionality. Refer Optional in-place filtering section at fileinput. The example below deletes the first line from a file:

import fileinput
import sys

for line_number, line in enumerate(fileinput.input('myFile', inplace=1)):
  if line_number == 0:
    continue
  else:
    sys.stdout.write(line)
Unbounded answered 18/5, 2013 at 13:36 Comment(0)
C
0

You cant delete a line from a file (or in very specific condition)

I would try to rewrite (in another file) all the content but the line, and then replace the original file with the new one.

This option only works if file is reasonnably small.

Deleting a specific line in a file (python)

Cutcheon answered 18/5, 2013 at 11:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.