8

I have a text file Thailand_Rectangle2_National Parks.txt with the following lines.

1
2
3
4
5
dy 0.5965
7

Now, I want to delete the 6th line in this text file.

For that, I am using the following python code.

f = open("C:/Users/Sreeraj/Desktop/Thailand_Rectangle2_National Parks.txt","r")
lines = f.readlines()

So, I saved all the lines of this text file in 'lines'.

line6 = lines[5]
t = line6[:2]
f.close() 

So, now, I have 't' = "dy" . Now,

if t == "dy":
    f = open("C:/Users/Sreeraj/Desktop/Thailand_Rectangle2_National Parks.txt","w")
    for line in lines:
        if lines[5] != line6:
            f.write(line)

f.close()

So, if the condition 't' = "dy" satisfies, then I will open this text file for writing and I will print all the lines except line6 (which means line6 is deleted from this text file).

Unfortunately, I am getting the lines in this text file as blank, which means no lines are printed as outputs.

But, I want the lines in the text file as given below.

1
2
3
4
5
7

How can I solve this issue ?

I want to use only Python programming to solve this issue; since this is a small task of a major work.

Sreeraj
  • 240
  • 1
  • 2
  • 12
  • Not sure why this is closed as a duplicate because although the title of the two questions are the same, the other question does not ask how to delete a specific line number. – Kurt Aug 05 '22 at 13:06

4 Answers4

13

Your problem is that lines[5] will always be equal to line6. You never modified the sixth line in lines, so line6 and lines[5] are still equal. Thus, the condition lines[5] != line6 will always fail.

If you want to always remove the sixth line from your file, you can use enumerate. For example:

with open("file.txt", "r") as infile:
    lines = infile.readlines()

with open("file.txt", "w") as outfile:
    for pos, line in enumerate(lines):
        if pos != 5:
            outfile.write(line)
Christian Dean
  • 22,138
  • 7
  • 54
  • 87
4

The error in your code was already pointed out, but instead of comparing the content of each line, I recommend you simply compare the line number or use startswith. Otherwise you are doing a lot of unneeded string comparisons, which can be costly.

Other improvements could be to handle your file using with, opening the file only once and allowing to delete multiple lines at once.

# 'r+' allows you to read and write to a file
with open("test.txt", "r+") as f:
    # First read the file line by line
    lines = f.readlines()

    # Go back at the start of the file
    f.seek(0)

    # Filter out and rewrite lines
    for line in lines:
        if not line.startswith('dy'):
            f.write(line)

    # Truncate the remaining of the file
    f.truncate()
Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
  • 1
    This is incorrect. After `readlines()` the file cursor is at the end of the file, so all writes append to the end, thus the final file will have _more_ lines than it originally had. Also, `startwith()` should be `startswith()`. – nh2 Mar 18 '20 at 23:44
  • 1
    @nh2 Thanks for pointing out. I don't remember what I thought at the time, but it simply seems I forgot to seek(0) after reading all lines. You can have a look at the fixed solution. – Olivier Melançon Mar 19 '20 at 12:43
2

You should check your logic and variable names. You're checking if lines[5] is not equal to line6, everytime in your loop. Which it is, because it IS that exact line. You want the check the current line:

if t == "dy":
    f = open("C:/Users/Sreeraj/Desktop/Thailand_Rectangle2_National Parks.txt","w")
    for line in lines:
        if line != line6: # <- Check actual line!
            f.write(line)

f.close()
The Pjot
  • 1,801
  • 1
  • 12
  • 20
0

You know that line6 == lines[5], so the condition if lines[5] != line6: is never true and thus you never write anything to the file