File Data Helper Functions in Python
Read and write text and JSON files, and list files in a directory, using pathlib-based helper functions.
Python code
54 linesfrom pathlib import Path
def load_text_file(filepath):
"""Read a text file and return its contents as a string."""
path = Path(filepath)
if not path.exists():
raise FileNotFoundError(f"File not found: {filepath}")
return path.read_text(encoding="utf-8")
def save_text_file(filepath, content):
"""Write content to a text file."""
path = Path(filepath)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content, encoding="utf-8")
return f"Saved {len(content)} characters to {filepath}"
def load_json_file(filepath):
"""Read a JSON file and return parsed data."""
import json
path = Path(filepath)
if not path.exists():
raise FileNotFoundError(f"File not found: {filepath}")
with path.open("r", encoding="utf-8") as f:
return json.load(f)
def save_json_file(filepath, data):
"""Save data as a JSON file with nice formatting."""
import json
path = Path(filepath)
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
return f"Saved JSON data to {filepath}"
def list_files_in_directory(directory):
"""Return a list of all files in a directory."""
path = Path(directory)
if not path.is_dir():
raise NotADirectoryError(f"Not a directory: {directory}")
return [p.name for p in path.iterdir() if p.is_file()]
if __name__ == "__main__":
# Demo usage
file_text = "Hello, PythonSkillset!\nThis is a sample file."
save_result = save_text_file("demo_files/sample.txt", file_text)
print(save_result)
print("Loaded text:", load_text_file("demo_files/sample.txt"))
demo_data = {"name": "Python", "version": 3.9, "features": ["simple", "powerful"]}
save_json_result = save_json_file("demo_files/data.json", demo_data)
print(save_json_result)
print("Loaded JSON:", load_json_file("demo_files/data.json"))
print("Files in demo_files:", list_files_in_directory("demo_files"))
Output
Saved 46 characters to demo_files/sample.txt
Loaded text: Hello, PythonSkillset!
This is a sample file.
Saved JSON data to demo_files/data.json
Loaded JSON: {'name': 'Python', 'version': 3.9, 'features': ['simple', 'powerful']}
Files in demo_files: ['sample.txt', 'data.json']
How it works
The pathlib.Path class provides cross-platform file operations with readable paths, replacing raw string manipulation for filesystem paths. Path.exists() and Path.is_dir() perform safety checks before reading or listing, and raise specific exceptions when the path is missing or wrong type. Directories are created automatically with mkdir(parents=True, exist_ok=True), making the save helpers safe to call on fresh projects. json.dump with indent=2 and ensure_ascii=False produces readable, human-friendly output that preserves non-ASCII characters. The functions return informative strings for saves, making them easy to use interactively or in quick scripts.
Common mistakes
- Using `open()` without a context manager, leaving file handles open
- Forgetting to create parent directories before writing to a nested path
- Assuming `list_files_in_directory` returns paths instead of names
- Mixing up `json.load` (file) and `json.loads` (string) APIs
Variations
- Use `pathlib.Path.read_bytes()` / `write_bytes()` for binary files like images.
- Replace manual existence checks with `try/except FileNotFoundError` for a more idiomatic approach.
Real-world use cases
- A setup script that writes the same default config and data files across developer machines.
- A small ETL job that reads raw text logs, then saves cleaned results as JSON for the next pipeline step.
- A CLI tool that lists files in a user-specified directory so users can inspect or pick an input 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.