Programming

How to Read and Write Files in Python (The Complete Guide)

Stop losing your data every time your script closes. Learn exactly how to read and write files in Python with this straightforward, step-by-step guide.

Modern Age Coders
Modern Age Coders April 12, 2026
9 min read
How to Read and Write Files in Python

You just built a brilliant Python script, but the second you close your terminal, all your hard-earned data disappears. Because variables and loops only live in your computer's short-term memory (RAM), learning to save persistent data directly to a hard drive is essential.

While dealing with file paths and access modes can feel frustrating at first, managing file systems in Python quickly becomes second nature. In this guide, we will break down exactly how to read and write files in Python, modern best practices for managing data, and how to avoid the most common errors that crash your scripts.

The Basics: How Python Thinks About Files

Interacting with a file in Python requires three distinct steps: you have to "open" a connection to the file, move your data back and forth, and then "close" the connection so other programs on your computer can use it.

You do not need to install any external libraries to do this. Python handles it natively through the built-in open() function.

When you open a file, you have to tell Python exactly what you plan to do with it. You do this by passing an "access mode" to the function. While there are several modes available, there are three essential ones you must memorize:

  • 'r' (Read): Look at the data, but do not touch it. If the file does not exist, Python will throw an error.
  • 'w' (Write): Write new data. Be incredibly careful with this mode: it will permanently erase everything that was previously in the file before adding your new text. If the file does not exist, Python will create it for you.
  • 'a' (Append): Add new data to the very end of the file without deleting the old stuff.

While this guide focuses heavily on standard text files, understanding different file types in Python (like CSVs or JSONs) is a logical next step, as the exact same reading and writing principles apply across the board.

How to Write Data to a File

Let's start by creating a brand new text file and putting some data inside it. We will use the 'w' mode.

# Open a file named 'data.txt' in write mode
file = open('data.txt', 'w')

# Write a string to the file
file.write("Hello, this is my first line of text.")

# Always close the file when you are done!
file.close()

If you run this script, a new file named data.txt will instantly appear in the same folder as your Python script.

There is one major catch that trips up almost every beginner. When you use the print() function, Python automatically drops you down to a new line. The write() function does not do that. If you write multiple strings in a row, they will just mash together into one giant, unreadable block of text. You have to manually add the newline character (\n) to the end of your strings.

file = open('data.txt', 'w')
file.write("This is line one.\n")
file.write("This is line two.\n")
file.close()

If you want to build a script that acts as a logbook—adding new entries over time without wiping the slate clean—you switch from 'w' to 'a' (append mode).

file = open('data.txt', 'a')
file.write("This line is added to the end without deleting the old ones.\n")
file.close()

For a deeper technical dive into the standard library and how the system encodes these characters, you can reference the official Python File I/O documentation.

How to Read Data from a File

Now that we have data saved on our hard drive, how do we get it back into our Python script? You open the file using the 'r' mode. Python gives you three different methods to extract your data efficiently, depending on how large the file is.

Method 1: file.read()

This grabs the entire document and returns it as one massive string. This is great for small text files, but it is a terrible idea for massive datasets. If you try to read() a 10GB log file, it will try to load all 10GB into your computer's RAM, crashing your system.

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

Method 2: file.readline()

This reads a single line at a time. Every time you call the function, it moves to the next line. This is perfect for parsing through heavy server logs without eating up your computer's memory.

file = open('data.txt', 'r')
first_line = file.readline()
print(first_line)
file.close()

Method 3: file.readlines()

This reads the entire file and chops it up, returning a Python List where every single line is a separate item. This is incredibly useful if you need to loop over the data or search for specific keywords.

To keep your main codebase clean, it is highly recommended to wrap your reading logic inside custom blocks. Understanding the advantages of functions in Python ensures that your file-reading code doesn't clutter up the rest of your program.

The with open() Context Manager (Why You Need It)

If you noticed in the examples above, we had to type file.close() every single time we were done.

Forgetting to close a file is the single most common mistake in Python file handling. If you don't close the file, it stays locked. Other programs won't be able to edit it, your changes might not actually save to the hard drive, and you will eventually cause a memory leak.

To solve this, modern Python developers do not use the standard open() and close() functions. Instead, they use a Context Manager, specifically the with open() syntax.

with open('data.txt', 'r') as file:
    content = file.read()
    print(content)
    # You do not need to write file.close() here!

How does this work? The with block acts as a protective wrapper. The second the indented code finishes running, Python automatically closes the file for you. Even better, if your program crashes or throws an error halfway through reading the file, the context manager still forces the file to close safely.

This is the industry gold standard. If you want a rock-solid foundation on syntax like this, bookmark our comprehensive Python for beginners guide.

Handling Exceptions and File Errors

What happens if you tell Python to read data.txt, but you accidentally deleted the file yesterday?

The program throws a FileNotFoundError and crashes entirely. You never want your user to see a massive block of red error text. Instead, you should wrap your file operations in a try-except block. This allows the program to gracefully catch the error and politely tell the user what went wrong without shutting down.

try:
    with open('missing_data.txt', 'r') as file:
        content = file.read()
except FileNotFoundError:
    print("Oops! It looks like that file does not exist. Please check the name.")

Using try-except blocks is mandatory when building real applications, because you can never guarantee that a file hasn't been moved, deleted, or renamed by the user. For advanced parsing techniques, checking out a community resource like Real Python's guide on Reading and Writing Files will help you take your error handling to the next level.

Conclusion

Reading and writing files is the critical bridge between writing temporary practice scripts and building permanent, useful software. Once you know how to save variables and lists to your hard drive, you can build practically anything.

Your challenge today: open your code editor and build a simple command-line diary. Ask the user for their thoughts using input(), and append their answer to a text file. Run it a few times and watch your text file grow.

Ready to upgrade your backend logic and build projects that actually matter? Explore the complete Python masterclasses at Modern Age Coders, where we teach you how to write production-level code.

Modern Age Coders

About Modern Age Coders

Expert educators passionate about making coding accessible and fun for learners of all ages.

Ask Misti AI
Chat with us