Working with files is common in many Python applications, especially in data processing, configuration management, and logging. Python offers built-in libraries and modules that make it straightforward to handle various file formats, such as .txt
, .csv
, and .json
. In this article, we’ll explore how to read and write files using Python.
Different modes for opening a file
In Python, when we open a file using the open()
function, we must specify the mode we want to which specifies what we want to do with the file. Here are the common modes available:
Mode | Description | Behavior |
---|---|---|
r |
Read-only mode. | Opens the file for reading. File must exist; otherwise, it raises an error. |
rb |
Read-only in binary mode. | Opens the file for reading binary data. File must exist; otherwise, it raises an error. |
r+ |
Read and write mode. | Opens the file for both reading and writing. File must exist; otherwise, it raises an error. |
rb+ |
Read and write in binary mode. | Opens the file for both reading and writing binary data. File must exist; otherwise, it raises an error. |
w |
Write mode. | Opens the file for writing. Creates a new file or truncates the existing file. |
wb |
Write in binary mode. | Opens the file for writing binary data. Creates a new file or truncates the existing file. |
w+ |
Write and read mode. | Opens the file for both writing and reading. Creates a new file or truncates the existing file. |
wb+ |
Write and read in binary mode. | Opens the file for both writing and reading binary data. Creates a new file or truncates the existing file. |
a |
Append mode. | Opens the file for appending data. Creates a new file if it doesn’t exist. |
ab |
Append in binary mode. | Opens the file for appending binary data. Creates a new file if it doesn’t exist. |
a+ |
Append and read mode. | Opens the file for appending and reading. Creates a new file if it doesn’t exist. |
ab+ |
Append and read in binary mode. | Opens the file for appending and reading binary data. Creates a new file if it doesn’t exist. |
x |
Exclusive creation mode. | Creates a new file. Raises an error if the file already exists. |
xb |
Exclusive creation in binary mode. | Creates a new binary file. Raises an error if the file already exists. |
x+ |
Exclusive creation with read and write mode. | Creates a new file for reading and writing. Raises an error if the file exists. |
xb+ |
Exclusive creation with read and write in binary mode. | Creates a new binary file for reading and writing. Raises an error if the file exists. |
Working with .txt
Files
Text files are the simplest form of files used for storing unstructured or lightly structured data.
Reading a .txt
File (General Way)
1 2 3 4 5 6 7 |
# general way to read text file file = open('example.txt','r') # r for file read content = file.read() print(content) file.close() |
Standard Way to Read .txt files
1 2 3 4 |
# Open and read a text file with open('example.txt', 'r') as file: content = file.read() print(content) |
Writing to a .txt
File
1 2 3 4 5 6 7 |
# Write to a text file (overwrite if exists) with open('example.txt', 'w') as file: file.write("This is a new line of text.\nAnother line here.") # Append to a text file with open('example.txt', 'a') as file: file.write("\nAppended line of text.") |
Working with .csv
Files, everything will be merged
CSV (Comma-Separated Values) files are used to store tabular data. Python provides a built-in A csv
module for reading and writing such files.
Reading a .csv
File
1 2 3 4 5 6 7 |
import csv # Read CSV into list of rows with open('data.csv', newline='') as csvfile: reader = csv.reader(csvfile) for row in reader: print(row) |
Writing to a .csv
File
1 2 3 4 5 6 7 8 9 10 11 12 |
import csv # Write list of rows to a CSV file data = [ ['Name', 'Age', 'City'], ['Alice', 30, 'New York'], ['Bob', 25, 'Los Angeles'] ] with open('output.csv', 'w', newline='') as csvfile: writer = csv.writer(csvfile) writer.writerows(data) |
Working with .json
Files
JSON (JavaScript Object Notation) is commonly used for storing structured data. Python’s json
module provides methods for parsing and writing JSON data.
Reading a .json
File
1 2 3 4 5 6 |
import json # Load JSON from a file with open('data.json', 'r') as json_file: data = json.load(json_file) print(data) |
Writing to a .json
File
1 2 3 4 5 6 7 8 9 10 11 |
import json # Write dictionary to a JSON file person = { "name": "Alice", "age": 30, "city": "New York" } with open('output.json', 'w') as json_file: json.dump(person, json_file, indent=4) |
Working with .json
Files Using pandas
The the pandas
library is widely used for data analysis and makes reading and writing JSON files especially simple, particularly when the data is structured like a table (i.e., records or arrays of dictionaries).
1 2 3 4 5 6 7 |
import pandas as pd # Read JSON file into a DataFrame df = pd.read_json('data.json') # Display the DataFrame print(df) |
Writing to a .json
File
1 2 3 4 5 6 7 8 9 10 11 12 |
import pandas as pd # Create a sample DataFrame data = { "name": ["Alice", "Bob"], "age": [30, 25], "city": ["New York", "Los Angeles"] } df = pd.DataFrame(data) # Write DataFrame to a JSON file df.to_json('output.json', orient='records', indent=4) |
Conclusion
Python’s standard libraries provide efficient tools for reading from and writing to .txt
, .csv
, and .json
files. By using simple methods such as open()
, csv.reader()
, and json.load()
, you can handle file operations effectively in your applications. These capabilities are especially useful in data analysis, configuration management, and integration with external systems.
Leave a Comment