(copied from https://github.com/blutterfly/python/blob/main/docs/examples/file_io.md on 2025-10-21 - thank you 'butterfly'/Larry Prestosa)
Quick reference and examples on writing, saving, and reading files.
Along with template functions for working with plain text, CSV, and JSON files.
Plain text files are the simplest type of file. You can write strings to them or read their content as text.
Writing to a Plain Text File
def write_to_text_file(file_path, text):
with open(file_path, 'w') as file: # Open file in write mode
file.write(text) # Write text to the fileReading from a Plain Text File
def read_from_text_file(file_path):
with open(file_path, 'r') as file: # Open file in read mode
return file.read() # Return the content of the fileExample Usage
write_to_text_file('example.txt', 'Hello, World!')
content = read_from_text_file('example.txt')
print(content)CSV (Comma-Separated Values) files are used to store tabular data.
Writing to a CSV File
import csv
def write_to_csv(file_path, data):
with open(file_path, 'w', newline='') as file: # Open file in write mode
writer = csv.writer(file)
writer.writerows(data) # Write rows of dataReading from a CSV File
def read_from_csv(file_path):
with open(file_path, 'r') as file: # Open file in read mode
reader = csv.reader(file)
return list(reader) # Convert rows to a listExample Usage
data = [
['Name', 'Age', 'Grade'],
['Alice', 16, 'A'],
['Bob', 17, 'B']
]
write_to_csv('students.csv', data)
content = read_from_csv('students.csv')
for row in content:
print(row)JSON (JavaScript Object Notation) is used to store structured data, such as dictionaries or lists.
Writing to a JSON File.
import json
def write_to_json(file_path, data):
with open(file_path, 'w') as file: # Open file in write mode
json.dump(data, file, indent=4) # Write data to the file in JSON formatReading from a JSON File.
def read_from_json(file_path):
with open(file_path, 'r') as file: # Open file in read mode
return json.load(file) # Load data from JSON fileExample Usage.
data = {
'students': [
{'name': 'Alice', 'age': 16, 'grade': 'A'},
{'name': 'Bob', 'age': 17, 'grade': 'B'}
]
}
write_to_json('students.json', data)
content = read_from_json('students.json')
print(content)| File Type | Python Module | Best for |
|---|---|---|
| Plain Text | open() |
Storing simple text or logs |
| CSV | csv |
Tabular data |
| JSON | json |
Structured data (hierarchical) |
Each of these functions can be adapted based on specific requirements.
- Python data I/O Cheat Sheet. https://www.fabriziomusacchio.com/.../python_data_io
- Python File I/O Cheat Sheet. https://www.cse.msu.edu/.../files-cheat-sheet.pdf