WindowsMacSoftwareSettingsSecurityProductivityLinuxAndroidPerformanceConfigurationApple All

How to Read and Write Files in Python

Edited 3 weeks ago by ExtremeHow Editorial Team

PythonFile HandlingIO OperationsWindowsMacLinuxProgramming BasicsIntermediateData ManagementScripting

How to Read and Write Files in Python

This content is available in 7 different language

Learning how to read and write files in Python is an essential skill for any programmer. Files contain data that can be read by a program or modified and saved for later use. In Python, file handling is simple and intuitive. This guide will introduce you to the basics and advanced concepts of file handling in Python using the built-in open function. We will explore different file modes, error handling, and various common use case scenarios.

Understanding file operations

Before getting into file operations in Python, it is important to understand what it means to read and write a file.

Opening a file

To read or write a file in Python, you must first open it. Python has a built-in open function. This function opens a file, returning a file object. The syntax of the open function is:

file_object = open(filename, mode)

Here, filename is the name of the file to be opened and mode indicates the purpose for which the file is being opened.

File mode

File modes determine how the file will be used once it is opened. Here are some common file modes:

Reading from a file

Once a file is opened in the appropriate mode, you can read its contents using methods such as read(), readline(), and readlines().

Using read() method

read() method reads the entire contents of the file and returns it as a string.

# Open the file in read mode
file_object = open("example.txt", "r")
# Read all the content
content = file_object.read()
# Print the content
print(content)
# Close the file
file_object.close()

Using readline() method

readline() method reads a line from the file and returns it as a string.

# Open the file
file_object = open("example.txt", "r")
# Read first line
first_line = file_object.readline()
# Print the first line
print(first_line)
# Close the file
file_object.close()

Using readlines() method

This method reads all the lines in the file and returns them as a list of strings. Each string represents a line in the file.

# Open the file
file_object = open("example.txt", "r")
# Read all lines
lines = file_object.readlines()
# Print all lines
for line in lines:
    print(line)
# Close the file
file_object.close()

Writing to a file

To write data to a file, you must open it in one of the writing modes ('w', 'a', or 'x'). write() and writelines() methods are used to write data to a file.

Using write() method

write() method writes a single string to a file.

# Open the file in write mode
file_object = open("example.txt", "w")
# Write data to the file
file_object.write("This is an example text.")
# Close the file
file_object.close()

Using writelines() method

writelines() method writes a list of strings to a file.

# Open the file in append mode
file_object = open("example.txt", "a")
# List of strings
lines = ["First line\n", "Second line\n", "Third line\n"]
# Write lines to the file
file_object.writelines(lines)
# Close the file
file_object.close()

Closing a file

It is important to close the file after using it. close() method is used for this purpose. It releases the resources used by the file.

# Properly closing a file
file_object.close()

You can also use the with statement to open a file. This approach ensures that the file is closed automatically, even if an exception is raised. Here's an example:

with open("example.txt", "r") as file_object:
    content = file_object.read()
    print(content)
# No need to explicitly close the file

Handling file exceptions

When working with files, errors may occur. Handling these errors gracefully improves the robustness of your program. Python provides a mechanism to handle such exceptions using try and except statements.

try:
    with open("example.txt", "r") as file_object:
        content = file_object.read()
        print(content)
except FileNotFoundError:
    print("The file does not exist.")
except IOError:
    print("Error occurred while accessing the file.")

In this example, if the file does not exist or cannot be accessed, a message is displayed, and the program continues execution without crashing.

Working with different file types

With Python, you can work with different file types, including text files, binary files, and others. The approach may vary slightly depending on the type of file:

Binary files

Binary files contain data in binary format. To handle binary files, open them in binary mode by adding 'b' to the file name (for example, 'rb' for binary read mode).

with open("image.jpg", "rb") as file_object:
    content = file_object.read()
    # Process binary content

CSV files

CSV (Comma-Separated Values) files are used to store tabular data. Python provides csv module to handle CSV files.

import csv
# Reading CSV
with open("data.csv", "r") as file_object:
    csv_reader = csv.reader(file_object)
    for row in csv_reader:
        print(row)
# Writing to CSV
with open("output.csv", "w", newline='') as file_object:
    csv_writer = csv.writer(file_object)
    csv_writer.writerow(["Header1", "Header2"])
    csv_writer.writerow(["Value1", "Value2"])

JSON files

JSON (JavaScript Object Notation) is a popular format for storing and exchanging data. Python's json module makes JSON file handling easy.

import json
# Reading JSON
with open("data.json", "r") as file_object:
    data = json.load(file_object)
    print(data)
# Writing JSON
with open("output.json", "w") as file_object:
    json.dump({"key": "value"}, file_object)

Advanced file operations

Search and recursion

The seek() method changes the position of the file object, allowing you to go to different locations in the file.

# Using seek to change file position
with open("example.txt", "r") as file_object:
    file_object.seek(5)
    content = file_object.read()
    print(content)

You can also use the file object as an iterator to iterate over the lines.

with open("example.txt", "r") as file_object:
    for line in file_object:
        print(line)

Summary

Handling files in Python is a basic skill that allows programmers to effectively store, retrieve, and manipulate data. This guide covered the basics of file reading and writing, explored various file modes, and showed how to handle exceptions. Additionally, it provided methods for working with various file types such as text, binary, CSV, and JSON files. With these tools, you can efficiently manage files in your Python program, ensuring that data is processed correctly and safely.

If you find anything wrong with the article content, you can


Comments