Home > database >  How to delete specific lines using their positions [closed]
How to delete specific lines using their positions [closed]

Time:10-06

For example, I have these lines:

simon
employed
reachel
employed
mark
employed

How do I delete line 3 and 4 without using the words "reachel" and "employed"?

CodePudding user response:

One way to do it would be to open the file, read the contents, remove what you want to remove, and re-write the file. This is assuming it is a text file called foo.txt:

file = "foo.txt"

with open(file, "r") as f:
     data = f.readlines()

del data[2]
del data[3]

with open(file, "w") as f:
    for item in data:
        f.write(item)

You remove the data directly from the list. Remember that the \n characters will be present, so if you want to make comparisons it is good to keep that in mind.

Here is more information on editing files: https://www.kite.com/python/answers/how-to-edit-a-file-in-python

CodePudding user response:

def delete_line(file_name, line_number):
    with open(file_name, 'r') as f:
        lines = f.readlines()

    with open(file_name, 'w') as f:
        for i, line in enumerate(lines):
            if i != line_number:
                f.write(line)


delete_line('test.txt', 1)
  • Related