Skip to content

Reading and writing TXT files

Plain text files contain only readable characters, such as notes, lists, or separated lines. They do not have a complex data structure. They are ideal for saving simple information such as logs, records, or unformatted text.

We have the following structure of our project:

  • Directorysrc
    • read_txt.py
    • write_txt.py
    • rewrite_txt.py
  • Directorydocs
    • story.txt

To read plain text files, Python offers a clear and safe syntax through the with statement, which guarantees the proper closing of the file once its reading is finished.

The following example opens a file called story.txt, goes through it line by line and prints its content, eliminating the line breaks at the end of each line:

read_txt.py
with open('./docs/story.txt', 'r') as file:
for line in file:
print(line.strip())

When you want to add text to the end of a file without overwriting its existing content, use the ‘a’ (append) mode. If the file does not exist, it is created automatically.

write_txt.py
# Add text
with open('./document/story.txt', 'a') as file:
file.write('\n\nBy: ChatGPT Nelson')

If you need to completely replace the content of a file, use the ‘w’ (write) mode. This mode creates the file if it does not exist, or deletes it and writes from scratch if it already exists.

write_txt.py
# Rewrite text
with open('./document/story1.txt', 'w') as file:
file.write('\n\nBy: PyDocs')