How to Read and Write Text Files in Python
This code provides simple helper functions to save and load text files using Python's standard pathlib library.
Python code
22 linesfrom pathlib import Path
def save_text_data(filename: str, content: str) -> None:
file_path = Path(filename)
file_path.write_text(content, encoding="utf-8")
def load_text_data(filename: str) -> str:
file_path = Path(filename)
return file_path.read_text(encoding="utf-8")
if __name__ == "__main__":
filename = "example_data.txt"
data_to_save = "Hello, this is beginner-friendly file data!\nSecond line here."
save_text_data(filename, data_to_save)
loaded_data = load_text_data(filename)
print("Saved and loaded content:")
print(loaded_data)
Output
Saved and loaded content:
Hello, this is beginner-friendly file data!
Second line here.
How it works
The save_text_data function uses Path.write_text to create or overwrite a file with the given content, specifying UTF-8 encoding for universal compatibility. The load_text_data function uses Path.read_text to read the entire file content as a string. These methods are concise and handle file opening and closing automatically, reducing boilerplate. The if __name__ == "__main__" guard ensures the test code only runs when the script is executed directly, not when imported as a module.
Common mistakes
- Forgetting to specify encoding, which can cause UnicodeDecodeError on systems with different default encodings
- Using `open()` without a context manager, risking file handles not being closed properly
- Assuming the file exists before reading without checking, leading to FileNotFoundError
Variations
- Use `open(filename, 'w')` and `open(filename, 'r')` with `with` statements for more explicit control
- Use `Path.write_bytes` and `Path.read_bytes` for binary data
Real-world use cases
- Persisting user preferences or application settings to a local text file
- Storing logs or small amounts of data from a script for later analysis
- Saving intermediate results in a data processing pipeline to a temporary file
Sponsored
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.