Python program to delete a specific line in a text file
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)
The actual error in your way to do this 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()
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()