Python File Operations: Reading, Writing, and Managing Files
This guide demonstrates Python techniques for reading, writing, and manipulating various file types—including text, binary, CSV, and JSON—while also covering file existence checks, renaming, deletion, and directory handling using os and shutil modules.
File Reading: Opening the Door to Knowledge
Basic reading of a text file:
with open('example.txt', 'r') as file:
content = file.read()
print(content)Reading a file line by line:
with open('example.txt', 'r') as file:
for line in file:
print(line.strip())Reading a specific number of lines:
with open('example.txt', 'r') as file:
lines = [next(file) for _ in range(5)]
print(lines)File Writing: Leaving Your Mark
Writing to a new file:
with open('output.txt', 'w') as file:
file.write("Hello, world!\n")Appending content to an existing file:
with open('output.txt', 'a') as file:
file.write("More text to append.\n")Writing multiple lines from a list:
lines = ["First line\n", "Second line\n"]
with open('output.txt', 'w') as file:
file.writelines(lines)File Operations: More Control
Check if a file exists:
import os
if os.path.exists('example.txt'):
print("File exists!")Rename a file:
os.rename('old_name.txt', 'new_name.txt')Delete a file:
os.remove('example.txt')Get file size:
size = os.path.getsize('example.txt')
print(f"File size: {size} bytes")Binary File Operations
Read a binary file:
with open('image.png', 'rb') as file:
image_data = file.read()
print(type(image_data))Write binary data to a file:
data = b'\x00\x01\x02\x03'
with open('binary_file.bin', 'wb') as file:
file.write(data)CSV File Operations
Read a CSV file:
import csv
with open('data.csv', newline='') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row)Write data to a CSV file:
import csv
data = [['Name', 'Age'], ['John', '25'], ['Jane', '30']]
with open('output.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(data)JSON File Operations
Read a JSON file:
import json
with open('data.json') as file:
data = json.load(file)
print(data)Write data to a JSON file:
import json
data = {"name": "John Doe", "age": 30}
with open('output.json', 'w') as file:
json.dump(data, file)Using shutil to Copy and Move Files
Copy a file:
import shutil
shutil.copy('source.txt', 'destination.txt')Move a file:
import shutil
shutil.move('source.txt', 'new_destination.txt')Using os to Delete Directories
Delete an empty directory:
import os
os.rmdir('empty_directory')Recursively delete a directory and its contents:
import shutil
shutil.rmtree('directory_to_delete')These examples showcase Python's powerful file handling capabilities, enabling efficient work with images, audio, and structured data across various projects.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.