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
Read a TXT file
Section titled “Read a TXT file”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:
with open('./docs/story.txt', 'r') as file:for line in file:print(line.strip())
Add content
Section titled “Add content”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.
# Add textwith open('./document/story.txt', 'a') as file:file.write('\n\nBy: ChatGPT Nelson')
Overwrite content
Section titled “Overwrite content”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.
# Rewrite textwith open('./document/story1.txt', 'w') as file:file.write('\n\nBy: PyDocs')