Python Language – Reading and Writing Files

Reading and Writing Files in Python

Working with files is a common task in Python programming. Whether you need to read data from external files or save the results of your program to a file, Python provides efficient ways to handle these operations. In this guide, we’ll explore reading and writing files in Python, covering various techniques and best practices.

Reading from Files

Python offers several methods for reading data from files, such as:

  • Using `read()`: This method reads the entire content of the file into a string.
  • Using `readline()`: It reads a single line from the file and moves the file pointer to the next line.
  • Using `readlines()`: This method reads all lines from the file into a list.
Example:

Let’s read the contents of a file named ‘example.txt’ using the `read()` method:


file = open('example.txt', 'r')
content = file.read()
file.close()

print(content)
Writing to Files

To write data to a file, you can use the `write()` method. It allows you to add content to the file. If the file doesn’t exist, it will be created. If it does exist, the previous content will be replaced by the new data.

Example:

Here’s how you can write data to a file named ‘output.txt’:


file = open('output.txt', 'w')
data = "Hello, World!"
file.write(data)
file.close()
Appending to Files

If you want to add data to an existing file without overwriting its content, you can open the file in append mode (‘a’). The `write()` method will add data to the end of the file without affecting the existing content.

Example:

Let’s append a new line to a file named ‘log.txt’:


file = open('log.txt', 'a')
log_entry = "Error: File not found."
file.write(log_entry)
file.close()
Using the ‘with’ Statement

Python supports the ‘with’ statement, which simplifies file I/O and ensures that files are properly closed. When you use ‘with,’ the file is automatically closed when the block is exited, even if an exception occurs, which helps prevent resource leaks and data corruption.

Example:

Using the ‘with’ statement to read a file:


with open('example.txt', 'r') as file:
    content = file.read()

# The file is automatically closed when the block exits
print(content)
Working with Binary Files

Python can handle binary files by specifying ‘b’ mode in file operations. Binary files are used for non-text files, such as images, audio, and executables. When working with binary files, you read and write data as bytes.

Example:

Here’s how you can read and write a binary file:


# Read binary data from a file
with open('image.jpg', 'rb') as file:
    binary_data = file.read()

# Write binary data to a new file
with open('copy_image.jpg', 'wb') as file:
    file.write(binary_data)
Conclusion

Mastering file handling in Python is crucial for a wide range of applications. Whether you’re reading configuration files, processing data, or storing results, the ability to efficiently read from and write to files is a fundamental skill for any Python programmer. Understanding these techniques and using the ‘with’ statement for file operations ensures proper resource management and data integrity.