File Handling
Python provides built-in functions and modules to work with files and directories. File handling allows us to create, read, write, append, and delete files. It also allows working with different file formats like text, CSV, and JSON.
Python’s built-in open() function is used to open a file. It requires a file path and a mode as arguments.
Common Modes Include:
- 'r' – Read mode (default): Opens a file for reading.
- 'w' – Write mode: Opens a file for writing (creates a new file or truncates an existing file).
- 'a' – Append mode: Opens a file for appending data to the end.
- 'r+' – Read and write mode: Opens a file for both reading and writing.
Using the with statement is recommended because it automatically closes the file after the block of code is executed.
1. Working with Text Files
Text files are the most common type of file you will work with. They contain plain text and can be manipulated line by line or as a whole string.
Basic Text File Handling
file = open('example.txt', 'r') # modes: 'r', 'w', 'a', 'b', 'x'
Writing to a File
file = open('example.txt', 'w')
file.write("Hello, World!")
file.close()
Reading a File
content = file.read()
lines = file.readlines()
line = file.readline()
file.close()
Appending to a File
file = open('example.txt', 'a')
file.write("\nNew line added.")
file.close()
Closing a File
file.close()
Using with Statement (Best Practice)
with open('example.txt', 'r') as file:
content = file.read()
2. Working with CSV Files
CSV (Comma-Separated Values) files store tabular data. Python’s built-in csv module makes it easy to read from and write to CSV files.
Writing to a CSV File
import csv
header = ['Name', 'Age', 'City']
data = [
['Alice', 30, 'New York'],
['Bob', 25, 'Los Angeles']
]
with open('test.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(header) # Write header
writer.writerows(data) # Write multiple rows
Reading from a CSV File
import csv
with open('test.csv', newline='') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row)
Using DictReader and DictWriter
with open('test.csv') as file:
reader = csv.DictReader(file)
for row in reader:
print(row['Name'])
Note: You can also use csv.DictReader and csv.DictWriter if you prefer to work with dictionaries (with column names as keys).
3. Working with JSON Files
JSON (JavaScript Object Notation) is a lightweight data interchange format. Python’s json module is used for reading and writing JSON data.
Writing JSON
import json
data = {
"name": "Alice",
"age": 30,
"city": "New York"
}
with open('data.json', 'w') as jsonfile:
json.dump(data, jsonfile, indent=4)
Reading JSON
import json
with open('data.json', 'r') as jsonfile:
data = json.load(jsonfile)
print(data)
indent parameter in json.dump() is used to format the JSON file with indentation for better readability.
4. Working with Directories
Python’s os and os.path modules are used for directory operations.
Creating a Directory
import os
os.mkdir('new_folder')
Listing Files in a Directory
files = os.listdir('.')
Checking if File or Directory Exists
os.path.exists('data.csv')
os.path.isdir('my_folder')
os.path.isfile('example.txt')
Removing Files or Directories
os.remove('data.csv') # Remove a file
os.rmdir('new_folder') # Remove an empty folder
Renaming Files or Folders
os.rename('old_name.txt', 'new_name.txt')
✅ Summary: Python File Handling
- File Handling Basics: Use
open()with appropriate modes ('r', 'w', 'a', 'r+') and thewithstatement for safe file management. - Text Files: Easily read and write using
read(),write(),readline(), andreadlines(). - CSV Files: The
csvmodule enables structured reading/writing of tabular data; useDictReader/DictWriterfor column-based access. - JSON Files: Use the
jsonmodule for storing and retrieving data in a human-readable and portable format. - Directories: The
osmodule provides tools to create, list, rename, or delete files and directories.
🔍 These file-handling techniques are essential for building robust applications, automating tasks, and processing various data types in Python.