Let's say I have a text file full of nicknames. How can I delete a specific nickname from this file, using Python?
First, open the file and get all your lines from the file. Then reopen the file in write mode and write your lines back, except for the line you want to delete:
with open("yourfile.txt", "r") as f: lines = f.readlines() with open("yourfile.txt", "w") as f: for line in lines: if line.strip("\n") != "nickname_to_delete": f.write(line)
You need to
strip("\n") the newline character in the comparison because if your file doesn't end with a newline character the very last
line won't either.
Solution to this problem with only a single open:
with open("target.txt", "r+") as f: d = f.readlines() f.seek(0) for i in d: if i != "line you want to remove...": f.write(i) f.truncate()
This solution opens the file in r/w mode ("r+") and makes use of seek to reset the f-pointer then truncate to remove everything after the last write.