Python File Handling Basics: Reading, Writing, and Using with

Python

Introduction

Working with files is a common task in many Python projects—whether it’s reading configuration files, saving logs, or processing data. In this guide, you’ll learn how to open, read, write, and properly close text files in Python. We’ll also cover how to use the with statement to manage files more safely and cleanly.

Opening and Writing to a File

To create and write to a text file, use the open() function with write mode ('w'):

file = open("example.txt", "w")
file.write("Hello, world!")
file.close()

Always remember to close the file after writing to ensure that changes are saved.

Reading from a File

To read a file, use read mode ('r'):

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

You can also read line-by-line using readline() or readlines().

Using the with Statement

Python’s with statement automatically manages file opening and closing. It’s the recommended way to handle files.

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

The file is automatically closed when the block is exited, even if an error occurs.

Appending to a File

To add new content without erasing existing data, use append mode ('a'):

with open("example.txt", "a") as file:
    file.write("\nAnother line.")

Conclusion

Understanding file operations in Python opens the door to a wide range of automation and data processing tasks. By using open, read, write, and especially the with statement, you can manage files cleanly and efficiently.

Related Articles

Comment

Copied title and URL