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 can specify different modes for different operations. Here are the common modes available:
- r (Read mode): Opens the file for reading. This is the default mode if no mode is specified.
- w (Write mode): Opens the file for writing. Creates a new file if it does not exist or truncates (empties) the file if it exists.
- a (Append mode): Opens the file for appending. Any data written to the file is automatically added to the end. It creates a new file if it does not exist.
- r+ (Read and Write mode): Opens the file for both reading and writing. The file pointer is placed at the beginning of the file.
- w+: Opens the file for both writing and reading. Like
’w’
, it creates a new file or truncates the existing file. - a+ (Append and Read mode): Opens the file for reading and appending. Like
’a’
, it creates a new file if it does not exist. The file pointer is at the end of the file if the file exists. - b (Binary mode): This mode is used with other modes (e.g.,
’rb’
,’wb’
,’ab+’
) for reading, writing, or appending in binary format. This is useful for non-text files like images or executable files. - t (Text mode): This is the default mode and can be combined with other modes like
’rt’
,’wt+’
, etc. It indicates the file is a text file.
1. Working with .txt
Files
Text files are the simplest form of files used for storing unstructured or lightly structured data.
Reading a .txt
File
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.") |
2. 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) |
3. 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) |
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