To read from or write to a file on your computer's disk, you first need to establish a connection to it from your Python script. This process is known as "opening" the file. Python provides a built-in function, open()
, specifically for this purpose.
open()
FunctionThe open()
function is straightforward to use. At its most basic, it requires the name (and potentially the path) of the file you want to work with and a mode specifying what you intend to do with the file (like reading from it or writing to it).
The basic syntax looks like this:
file_object = open('filename', 'mode')
Let's break down the arguments:
filename
: This is a string representing the name of the file you wish to open. If the file is in the same directory as your Python script, you can just provide the filename (e.g., 'notes.txt'
). If the file is located elsewhere, you'll need to provide the path to it. How paths are specified depends on your operating system (as discussed in the "Understanding File Paths" section). For example, you might use 'data/config.txt'
for a relative path or a full path like 'C:/Users/username/Documents/report.txt'
on Windows or '/home/user/documents/report.txt'
on Linux/macOS.
mode
: This is a string indicating how the file will be used. The mode determines what operations you are allowed to perform (like reading or writing) and how the file is handled if it already exists or doesn't exist. Here are the three most common modes for text files:
'r'
(Read Mode): This is the default mode if you don't specify one. It allows you to read data from an existing file. If the file doesn't exist, Python will raise a FileNotFoundError
.'w'
(Write Mode): This mode allows you to write data to a file. If the file already exists, its current contents will be erased completely before writing begins. If the file does not exist, a new, empty file will be created. Use this mode with caution, as it can overwrite existing data.'a'
(Append Mode): This mode allows you to add new data to the end of an existing file. If the file exists, the new data is simply appended. If the file does not exist, a new file is created (similar to write mode, but without erasing existing content if the file did exist).For example, to open a file named config.txt
for reading:
config_file = open('config.txt', 'r')
# Or simply, since 'r' is the default:
# config_file = open('config.txt')
To open (or create) a file named log.txt
for appending new entries:
log_file = open('log.txt', 'a')
To open (or create and overwrite) a file named output.txt
for writing:
output_file = open('output.txt', 'w')
When you successfully call open()
, it returns a file object (also sometimes called a file handle). This object acts as Python's link to the actual file on your disk. You'll use methods associated with this file object to perform operations like reading data from the file or writing data into it. In the examples above, config_file
, log_file
, and output_file
are variables holding these file objects.
After you finish performing operations on a file (reading, writing, or appending), it's very important to close it. Closing a file tells the operating system that you're done with it, which accomplishes several things:
close()
MethodPython file objects have a close()
method that you must call when you are finished with the file.
Here's a simple pattern:
# Open the file for writing
output_file = open('output.txt', 'w')
# Perform write operations (covered in the next sections)
output_file.write('This is the first line.\n')
output_file.write('This is the second line.\n')
# Explicitly close the file
output_file.close()
It's essential to remember to call close()
. However, there's a potential issue: what if an error occurs in your code after you've opened the file but before you reach the close()
call? In such cases, the file might remain open. Python provides a more robust way to handle file opening and closing using the with
statement, which guarantees the file is closed automatically, even if errors occur. We will cover this preferred method in the section "Using with
for Automatic File Closing". For now, understand that opening a file requires a corresponding close()
call when using this basic approach.
© 2025 ApX Machine Learning