The basic way to open a file in Python
To open a file in Python, use the open() function with the filename and the mode you want. The most common mode is 'r' for reading. Here's the simplest example:
If you have a file called data.txt in the same folder as your Python script, you can open it like this:
file = open('data.txt', 'r')
This creates a file object that you can then read from. However, this approach has a problem: if you forget to close the file, it stays open in memory. A better method is to use the with statement, which automatically closes the file when you're done:
with open('data.txt', 'r') as file: content = file.read() print(content)
The with statement is the standard way to open files in modern Python because it handles closing automatically, even if an error occurs while reading.
Key Takeaways
- Use the open() function with a filename and mode ('r' for reading, 'w' for writing, 'a' for appending) to open a file.
- Always use the with statement when opening files so Python closes them automatically when you're finished.
- The file path can be relative (same folder as your script) or absolute (the full path from your computer's root).
- Different file types (text, CSV, JSON) may need different reading methods, but the opening process is the same.
- If a file doesn't exist and you try to open it in read mode, Python raises a FileNotFoundError.
Understanding file modes
The second argument to open() tells Python what you want to do with the file. The most common modes are:
| Mode | What it does | Creates file if missing? |
|---|---|---|
| 'r' | Read only | No — raises error |
| 'w' | Write (overwrites existing content) | Yes |
| 'a' | Append (add to the end) | Yes |
| 'r+' | Read and write | No — raises error |
If you open a file in write mode ('w') and the file already exists, Python will erase all its contents and start fresh. If you want to add to a file instead of replacing it, use append mode ('a').
For reading, 'r' is the standard choice. If the file doesn't exist, Python will raise a FileNotFoundError, which is usually what you want because it tells you something went wrong.
Reading file content in different ways
Once you've opened a file, you have several options for reading it. The method you choose depends on what you're doing with the data.
read() reads the entire file as one string. This works well for small files but can use a lot of memory for large ones:
with open('data.txt', 'r') as file: content = file.read()
readlines() reads the entire file and returns a list of lines, with each line including the newline character at the end:
with open('data.txt', 'r') as file: lines = file.readlines() for line in lines: print(line)
Looping directly over the file object is the most memory-efficient way to read large files, because Python reads one line at a time instead of loading everything into memory:
with open('data.txt', 'r') as file: for line in file: print(line.strip())
The .strip() method removes the newline character at the end of each line, which is usually what you want when printing.
Handling file paths on different computers
File paths work differently on Windows, Mac, and Linux. On Windows, paths use backslashes (\), while Mac and Linux use forward slashes (/). Python can handle this automatically if you use the pathlib module, which is built into Python:
from pathlib import Path file_path = Path('data') / 'myfile.txt' with open(file_path, 'r') as file: content = file.read()
The / operator in pathlib works on all operating systems and automatically uses the correct slash for your computer. This is more reliable than typing the path as a string.
If your file is in a different folder, you can use relative paths (relative to where your script is) or absolute paths (the full address from your computer's root). For example, '../data/file.txt' goes up one folder and then into the data folder.
What to do when a file doesn't exist
If you try to open a file in read mode and it doesn't exist, Python raises a FileNotFoundError. You can handle this with a try-except block:
try: with open('data.txt', 'r') as file: content = file.read() except FileNotFoundError: print("File not found. Check the filename and path.")
This approach lets your program continue running instead of crashing. You can also check whether a file exists before trying to open it using pathlib:
from pathlib import Path file_path = Path('data.txt') if file_path.exists(): with open(file_path, 'r') as file: content = file.read() else: print("File does not exist.")
Opening specific file types
Text files open the same way regardless of content, but some file types need special handling. For CSV files (comma-separated values), Python's built-in csv module makes parsing easier:
import csv with open('data.csv', 'r') as file: reader = csv.DictReader(file) for row in reader: print(row)
For JSON files, use the json module:
import json with open('data.json', 'r') as file: data = json.load(file) print(data)
For binary files like images or PDFs, open them in binary mode by adding 'b' to the mode: 'rb' for reading binary or 'wb' for writing binary. Most of the time you'll use a specialized library for these files rather than reading them directly.
Common mistakes and how to avoid them
The most common mistake is forgetting to close files. Always use the with statement — it closes the file automatically. Never write file = open('data.txt') and then forget to call file.close() later.
Another mistake is using the wrong file path. If you get a FileNotFoundError, check that the filename is spelled correctly and that the file is actually in the folder you think it is. Print the current working directory with import os; print(os.getcwd()) to see where Python is looking.
Opening a file in write mode ('w') when you meant to use read mode ('r') will erase the file. Double-check your mode before running code that writes to files.
Trying to read a file that's already open in another program (like Excel or a text editor) can sometimes cause permission errors on Windows. Close the file in the other program first.
Frequently Asked Questions
What's the difference between read() and readlines()?
read() returns the entire file as one long string. readlines() returns a list where each item is one line, including the newline character. Use read() when you want the whole file at once, and readlines() when you want to work with individual lines.
Can I open a file that's in a different folder?
Yes. Use a relative path like '../data/file.txt' (go up one folder, then into data) or an absolute path like '/Users/yourname/Documents/file.txt' on Mac or 'C:\\Users\\yourname\\Documents\\file.txt' on Windows. The pathlib module handles path separators automatically across operating systems.
What happens if I open a file but don't close it?
The file stays open in memory until your program ends or Python's garbage collector closes it. This wastes memory and can prevent other programs from modifying the file. Always use the with statement, which closes the file automatically.
How do I open a file for both reading and writing?
Use mode 'r+' to open a file for reading and writing. The file must already exist. If you want to write and then read, or read and then write, you can also open the file twice in separate with blocks.
Why do I get a FileNotFoundError?
The file doesn't exist at the path you specified, or the path is wrong. Check the filename spelling, make sure the file is in the folder you think it is, and verify the path is relative to where your script runs. Use import os; print(os.getcwd()) to see the current working directory.