The basic way to open a file in Python
To open a file in Python, use the open() function with the filename and a mode that tells Python what you want to do with it. The simplest approach is to store the file in a variable, then read from it.
Here is the most common pattern:
file = open("myfile.txt", "r")
The "r" mode means read-only — you can look at the file but not change it. After you finish, close the file with file.close() so Python releases it and frees up memory.
If the file is in a different folder, include the path: open("Documents/myfile.txt", "r") on Mac or Linux, or open("Documents\\myfile.txt", "r") on Windows (note the backslashes).
Key Takeaways
- The open() function takes a filename and a mode — "r" for reading, "w" for writing, and "a" for adding to the end of a file.
- Always close a file after you finish with file.close(), or use a with statement to close it automatically.
- If Python cannot find the file, check that the filename is spelled correctly and that the file is in the location you specified or in your current working directory.
- Use read() to get the whole file as one string, readline() to get one line at a time, or loop through the file object directly to process it line by line.
File modes: read, write, and append
The second argument to open() is the mode, which controls what you can do with the file. The three most common modes are "r" (read), "w" (write), and "a" (append).
"r" opens the file for reading only. If the file does not exist, Python raises an error. "w" opens the file for writing — if the file exists, Python erases it and starts fresh; if it does not exist, Python creates it. "a" opens the file for appending, meaning you add new content to the end without erasing what is already there.
There are also modes that combine reading and writing, like "r+" (read and write) and "w+" (write and read), but these are less common for beginners. Stick with "r", "w", or "a" unless you have a specific reason to do both at once.
Reading file content: three methods
Once you open a file in read mode, you have three main ways to get the content out. The read() method returns the entire file as a single string, including all newline characters. This works well for small files but can use a lot of memory for large ones.
readline() returns one line at a time, including the newline character at the end. You can call it repeatedly to step through the file line by line. The readlines() method (note the plural) returns a list of all lines, which is useful if you want to work with the lines as separate items.
For most tasks, looping directly through the file object is the cleanest approach:
for line in file: print(line)
This reads one line at a time without loading the whole file into memory, and it works the same way whether the file has 10 lines or 10 million.
Using the with statement to close files automatically
Forgetting to close a file is a common mistake. The with statement solves this by closing the file automatically when you are done, even if an error occurs:
with open("myfile.txt", "r") as file: content = file.read()
Everything indented under the with line has access to the file. Once the indented block ends, Python closes the file automatically. This is the recommended way to open files in modern Python code because it prevents accidental memory leaks and is clearer to read.
You can also use with to open multiple files at once by separating them with commas:
with open("input.txt", "r") as infile, open("output.txt", "w") as outfile:
Handling errors when a file does not exist
If you try to open a file that does not exist in read mode, Python raises a FileNotFoundError. You can catch this error and handle it gracefully using a try-except block:
try: file = open("myfile.txt", "r")except FileNotFoundError: print("File not found")
This tells Python to try opening the file, and if it fails, run the code in the except block instead of crashing. You can also check whether a file exists before opening it by using the os.path.exists() function from Python's built-in os module, though the try-except approach is more common.
If you are opening a file for writing and it does not exist, Python creates it automatically, so you do not need to check first.
Working with different file types
Text files like .txt and .csv open the same way as shown above. For .csv files, you can use the csv module to parse the data into rows and columns automatically, rather than reading it as plain text.
For .json files, use the json module to convert the file content into Python dictionaries and lists. For .xlsx (Excel) files, you need a third-party library like openpyxl or pandas, which do not come with Python by default.
Binary files like images, videos, and compiled programs require opening in binary mode by adding a b to the mode string — for example, "rb" for reading binary. For most text-based work, the standard "r" mode is all you need.
Finding your current working directory
When you give Python a filename without a full path, it looks in the current working directory — the folder where your script is running. If the file is not there, Python cannot find it even if the file exists elsewhere on your computer.
To see your current working directory, use os.getcwd() from the os module. To change it, use os.chdir("path/to/folder"). Most of the time, it is easier to put your data files in the same folder as your Python script, or to use the full path to the file.
On Windows, backslashes in paths can cause problems because Python treats them as escape characters. Use forward slashes instead — "Documents/myfile.txt" works on all operating systems — or use raw strings by putting r before the path: r"Documents\myfile.txt".
Frequently Asked Questions
What is the difference between read(), readline(), and readlines()?
read() returns the entire file as one string. readline() returns one line at a time and must be called repeatedly. readlines() returns a list of all lines. For most tasks, looping directly through the file object is simpler and more memory-efficient than any of these.
Do I have to close a file after opening it?
Technically, Python closes the file automatically when the program ends, but closing it explicitly with file.close() or using a with statement is a best practice. It frees memory immediately and prevents errors if you open many files in a row.
How do I write to a file without erasing what is already in it?
Use mode "a" (append) instead of "w" (write). Mode "w" erases the file; mode "a" adds new content to the end. If you want to both read and write without erasing, use "r+" or "a+".
What does it mean if I get a FileNotFoundError?
Python cannot find the file you asked it to open. Check that the filename is spelled correctly, that the file actually exists, and that it is in the location you specified or in your current working directory. Use os.getcwd() to see where Python is looking.
Can I open a file from a website URL?
Not with the standard open() function — that only works with files on your computer. To open a file from the internet, use the urllib module or the third-party requests library to download the content first, then process it as a string.