Working with Files in Python
Working with files is a fundamental skill for any Python programmer. Whether you need to read data from a file, write logs to a file, or work with structured data like CSV or JSON, Python provides a simple and powerful API for file manipulation.
In this tutorial, we’ll cover the basics of file I/O (input/output) in Python.
Reading from Files
To read from a file in Python, you first need to open it using the built-in open() function. The open() function returns a file object, which you can then use to read the file’s contents.
The open() function takes two arguments: the path to the file and the mode in which to open it. The mode is a string that specifies how you want to interact with the file. The most common modes are:
'r': Read mode (the default).'w': Write mode. If the file already exists, its contents will be overwritten. If the file doesn’t exist, it will be created.'a': Append mode. If the file already exists, new data will be written to the end of the file. If the file doesn’t exist, it will be created.'b': Binary mode. This is used for working with non-text files, like images or audio files.'t': Text mode (the default).
Here’s an example of how to read the entire contents of a text file:
with open('example.txt', 'r') as f:
contents = f.read()
print(contents)The with statement is used here to ensure that the file is automatically closed after you’re done with it. This is a good practice to follow, as it helps to prevent resource leaks.
You can also read a file line by line, which is useful for large files that you don’t want to load into memory all at once:
with open('example.txt', 'r') as f:
for line in f:
print(line, end='')Writing to Files
To write to a file in Python, you need to open it in write ('w') or append ('a') mode.
Here’s an example of how to write a string to a file:
with open('example.txt', 'w') as f:
f.write('Hello, world!')If you open a file in write mode and it already exists, its contents will be overwritten. If you want to add to an existing file, you should open it in append mode:
with open('example.txt', 'a') as f:
f.write('\nThis is a new line.')Working with CSV Files
CSV (Comma-Separated Values) is a common format for storing tabular data. Python’s csv module makes it easy to work with CSV files.
Here’s an example of how to read data from a CSV file:
import csv
with open('example.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
print(row)And here’s an example of how to write data to a CSV file:
import csv
with open('example.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['name', 'age'])
writer.writerow(['Alice', 30])
writer.writerow(['Bob', 25])Working with JSON Files
JSON (JavaScript Object Notation) is another popular format for storing structured data. Python’s json module makes it easy to work with JSON files.
Here’s an example of how to read data from a JSON file:
import json
with open('example.json', 'r') as f:
data = json.load(f)
print(data)And here’s an example of how to write data to a JSON file:
import json
data = {
'name': 'Alice',
'age': 30,
'city': 'New York'
}
with open('example.json', 'w') as f:
json.dump(data, f)For more information on working with files in Python, you can refer to the official Python documentation: https://docs.python.org/3/tutorial/inputoutput.html