On this page
File Handling in Python
Reading from Files
Python provides built-in functions to read from files. The most common way is using the open()
function, followed by reading the file’s content.
- Opening a File:
file = open('filename.txt', 'r') # 'r' for read mode
- Reading the Entire File:
content = file.read()
print(content)
file.close() # Always close the file after reading
- Reading Line by Line:
with open('filename.txt', 'r') as file:
for line in file:
print(line.strip()) # .strip() removes extra whitespace
Using with open is recommended because it automatically handles file closing.
Writing to Files
You can write data to files using the write()
or writelines()
methods.
- Opening a File for Writing:
file = open('filename.txt', 'w') # 'w' for write mode, 'a' for append
- Writing a Single Line:
file.write("Hello, World!\n")
file.close()
- Writing Multiple Lines:
with open('filename.txt', 'w') as file:
lines = ["First line\n", "Second line\n", "Third line\n"]
file.writelines(lines)
Working with Different File Formats
Python provides specialized modules for working with various file formats like CSV and JSON.
- CSV Files:
import csv
# Reading CSV
with open('data.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
# Writing CSV
with open('output.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Age', 'City'])
writer.writerow(['Alice', 30, 'New York'])
- JSON Files:
import json
# Reading JSON
with open('data.json', 'r') as file:
data = json.load(file)
print(data)
# Writing JSON
with open('output.json', 'w') as file:
json.dump({'name': 'Alice', 'age': 30, 'city': 'New York'}, file, indent=4)
Let me know if you need more examples or explanations on any of these topics!