So far, your programs have probably read input from the keyboard and displayed output on the screen. But what if you need to work with large amounts of data or save your results permanently? Learning how to read and write files is the answer, allowing your programs to interact with data stored on your computer.
📂 Opening and Closing a File
Before you can read from or write to a file, you must first open it using the built-in open()
function. This function takes two main arguments: the file’s name and an access mode. The most common modes are "r"
for reading, "w"
for writing (which will overwrite any existing file), and "a"
for appending (adding to the end of an existing file). When you’re finished, it’s crucial to close the file using the .close()
method to ensure all changes are saved properly.inf = open("input.txt", "r")
# ... do stuff with the file ...
inf.close()
📖 Reading Data from a File
Once a file is opened in read mode, there are several ways to get its contents. The .readline()
method reads one line from the file at a time, returning it as a string. This is great for processing a file line-by-line in a loop. Alternatively, the .readlines()
method reads the entire file at once and returns a list where each element is a line from the file. Keep in mind that lines read from a file often have a hidden newline character at the end, which you can remove using the .rstrip()
method.
✍️ Writing Data to a File
To save data, you open a file in write ("w"
) or append ("a"
) mode. The .write()
method is used to store a string in the file. Unlike the print()
function, .write()
does not automatically add a newline at the end. You must explicitly add the newline character, \n
, if you want each piece of data on its own line.outf.write("Hello, world!\n")
outf.write("This is a new line.")
Working with files unlocks a huge range of possibilities for your programs, from saving user settings to analyzing massive datasets.
—
Stephenson, Ben. The Python Workbook: A Brief Introduction with Exercises and Solutions. 3rd ed., Springer, 2025.
More Topics
- How to Pass Command Line Arguments to Your Python Script
- Solving the Classic FizzBuzz Problem in Python: A Step-by-Step Tutorial
- How to Solve the Pythagorean Theorem with a Python Script
- What’s the Difference Between Syntax, Runtime, and Logic Errors in Python?
- What Are Dictionaries in Python and How Do You Use Them?
- Thinking Recursively: A Beginner’s Introduction to Recursion in Python
- How to Handle Errors Gracefully in Python with Try and Except