Python (Scripting) - Read and Write to the same file
by
Jeremy Canfield |
Updated: January 30 2024
| Python (Scripting) articles
Here is how you can read and write to the same file, removing lines matching "Hello World" from the file. This basically overwrites the entire file but simply does not include the lines containing "Hello World".
#!/usr/bin/python3
with open("/path/to/example.txt", "r+") as file:
file.readlines = file.read().splitlines()
file.seek(0)
for line in file.readlines:
print(line)
if line != "Hello World":
file.write(f"{line}\n")
file.truncate()
Did you find this article helpful?
If so, consider buying me a coffee over at