Python
How to Use “with” in Python to Open Files
March 1, 2023
This guide is part of the "Snippets" series. This series is focused on providing simple and accessible tutorials on various topics relating to development!
In Python, you can use the "with" statement to open files. The "with" statement ensures that the file is closed properly when the block inside the "with" statement is exited, even if an exception occurs. Here's an example:
with open('file.txt', 'r') as f:
content = f.read()
print(content)
In this example, the "with" statement opens the file "file.txt" in read mode and assigns it to the variable "f". The block inside the "with" statement reads the contents of the file using the "read" method, and prints it to the console.
You can also open files in write mode using the "with" statement, like this:
with open('file.txt', 'w') as f:
f.write('Hello, world!')
In this example, the "with" statement opens the file "file.txt" in write mode and assigns it to the variable "f". The block inside the "with" statement writes the string "Hello, world!" to the file using the "write" method.
Reading a CSV file using a CSV reader
import csv
with open('data.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
print(row)
In this example, the "with" statement opens the file "data.csv" in read mode and assigns it to the variable "f". The "csv.reader" function is used to create a CSV reader object, which can be used to read the contents of the CSV file. The "for" loop iterates over each row in the CSV file, and prints it to the console.
Writing to JSON files
import json
data = {'name': 'Alice', 'age': 30}
with open('data.json', 'w') as f:
json.dump(data, f)
In this example, the "with" statement opens the JSON file "data.json" in write mode and assigns it to the variable "f". The block inside the "with" statement uses the "json" module to write the Python dictionary "data" to the file as JSON data. Once the block is exited, the file is automatically closed due to the "with" statement.
Appending text to an existing file
with open('file.txt', 'a') as f:
f.write('Some more text\n')
In this example, we open the file "file.txt" in append mode by passing the 'a' argument to the "open" function. We then use the "write" method to append some text to the end of the file. The "\n" character at the end of the string is a newline character, which ensures that the text is added on a new line.