Bootstrap FreeKB - Python (Scripting) - Read and Write to the same file
Python (Scripting) - Read and Write to the same file

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


Please enter 9aa08a in the box below so that we can be sure you are a human.