Opening a file in Python means telling the program where the file lives and what you want to do with it

Python has a built-in function called open() that reads files from your computer. When you call it, you give Python two pieces of information: the name of the file and the mode — whether you want to read it, write to it, or add to the end of it. Python then creates a file object that you can work with in your code.

The simplest case is reading a file that already exists. You write open("filename.txt", "r"), where "r" means read mode. Python finds the file, opens it, and gives you back an object you can use to pull the contents into your program. Once you are done, you close the file with the close() method so Python releases it and frees up memory.

Key Takeaways

  • The open() function takes a filename and a mode ("r" for read, "w" for write, "a" for append) and returns a file object you can read from or write to.
  • Always close the file when you are done by calling .close() on the file object, or use a with statement to close it automatically.
  • The file path can be a straightforward name like "data.txt" if the file is in the same folder as your Python script, or a full path like "C:\Users\Documents\data.txt" on Windows.
  • Common modes are "r" (read), "w" (write and overwrite), and "a" (append to the end), and you can add "b" for binary files like images or PDFs.

The basic syntax for opening a file

The open() function takes at least two arguments. The first is the filename as a string, and the second is the mode. Here is the structure:

file_object = open("filename.txt", "r")

Python looks for "filename.txt" in the current working directory — the folder where your script is running. If the file is in a different folder, you need to provide the path. On Windows, that might look like open("C:\\Users\\YourName\\Documents\\filename.txt", "r"). On Mac or Linux, it looks like open("/Users/YourName/Documents/filename.txt", "r"). Notice that Windows paths use backslashes, but in Python strings you write two backslashes because one backslash is an escape character.

After open() runs, the variable file_object holds a reference to the file. You use this object to read the contents. When you are finished, call file_object.close() to close it.

Reading the contents of a file

Once you have opened a file in read mode, you have three main ways to get the contents into your program. The method you choose depends on how you want to work with the data.

read() pulls the entire file into memory as a single string. If you have a file called "message.txt" that contains "Hello World", then file_object.read() returns the string "Hello World". This works well for small files, but if the file is very large, it can use a lot of memory.

readline() reads one line at a time. Each time you call it, Python returns the next line as a string, including the newline character at the end. readlines() (with an "s") reads all lines and returns them as a list of strings, one per line. This is useful when you want to loop through a file line by line without loading everything into memory at once.

The most common pattern is to loop through the file object directly without calling any method:

for line in file_object:   print(line)

This reads one line at a time and stops when the file ends. It is memory-efficient and readable.

Using the with statement to close files automatically

Forgetting to close a file is a common mistake. If you open many files and forget to close them, your program can run out of file handles and crash. Python offers a safer way: the with statement.

with open("filename.txt", "r") as file_object:   contents = file_object.read()

The with statement opens the file, runs the indented code block, and then closes the file automatically — even if an error happens inside the block. You do not have to remember to call close(). This is the recommended way to open files in modern Python code.

The as file_object part gives the file a name you can use inside the block. After the block ends, the file is closed and you cannot use file_object anymore. If you try to read from it, Python raises an error.

Writing to a file

To create a new file or overwrite an existing one, use write mode by passing "w" as the second argument to open(). If the file does not exist, Python creates it. If it does exist, Python erases it and starts fresh.

with open("output.txt", "w") as file_object:   file_object.write("This is a new line.\n")

The write() method takes a string and writes it to the file. Notice the "\n" at the end — that is the newline character. Without it, the next write will appear on the same line.

If you want to add to the end of an existing file instead of overwriting it, use append mode "a":

with open("output.txt", "a") as file_object:   file_object.write("This line is added at the end.\n")

Append mode opens the file and moves to the end, so your new text appears after whatever was already there.

Handling file paths on different operating systems

File paths look different on Windows, Mac, and Linux, which can cause confusion. Windows uses backslashes (C:\Users\Documents\file.txt), while Mac and Linux use forward slashes (/Users/Documents/file.txt). If you write a path with backslashes in a Python string, you must escape them by writing two backslashes.

A more portable approach is to use the pathlib module, which handles paths correctly on any operating system:

from pathlib import Path file_path = Path("Documents") / "filename.txt" with open(file_path, "r") as file_object:   contents = file_object.read()

The / operator joins path parts together, and pathlib automatically uses the correct separator for your system. This is especially useful if your program needs to run on multiple operating systems.

Common errors and what they mean

The most common error is FileNotFoundError, which means Python looked for the file but could not find it. This usually happens because the filename is spelled wrong, the path is incorrect, or the file is in a different folder than you thought. Double-check the filename and the path, and make sure the file actually exists.

PermissionError means Python found the file but does not have permission to read or write it. On some systems, files have permissions that restrict who can access them. You may need to change the file permissions or run your program with administrator privileges.

IsADirectoryError means you tried to open a folder instead of a file. Make sure you are passing the full path to the file, not just the folder name.

If you try to read from a file that you opened in write mode, or write to a file you opened in read mode, Python raises a ValueError. Always use the correct mode for what you want to do.

Frequently Asked Questions

What is the difference between read mode and write mode?

Read mode ("r") opens a file so you can look at its contents, but you cannot change it. Write mode ("w") lets you create a new file or replace an existing one with new contents. If you want to add to the end of a file without erasing what is already there, use append mode ("a").

Do I have to close a file if I use the with statement?

No. The with statement closes the file automatically when the block ends. You do not need to call close() yourself. This is one reason the with statement is safer than opening and closing manually.

Can I open a file that is in a different folder?

Yes. Provide the full path to the file instead of just the filename. On Windows, use open("C:\\Users\\YourName\\Documents\\file.txt", "r"). On Mac or Linux, use open("/Users/YourName/Documents/file.txt", "r"). You can also use the pathlib module to build paths that work on any system.

What does the "b" in file modes like "rb" or "wb" mean?

The "b" stands for binary. Use it when working with files that are not plain text, such as images, PDFs, or audio files. For example, open("image.png", "rb") opens an image file in binary read mode so Python does not try to interpret it as text.

What happens if I try to open a file that does not exist in read mode?

Python raises a FileNotFoundError and stops running your code. If you want to handle this gracefully, you can use a try-except block to catch the error and run different code instead of crashing.