The basic way to open a file in Python

To open a file in Python, you use the open() function with the filename and the mode you want. The simplest version looks like this:

file = open("myfile.txt", "r")

This opens a file called myfile.txt in read mode, which means you can look at what is inside but not change it. The file object gets stored in a variable called file, and you can then read from it. When you are done, you close it with file.close().

The mode you choose matters. Read mode ("r") lets you look at the file. Write mode ("w") lets you create a new file or overwrite an existing one. Append mode ("a") lets you add to the end of a file without erasing what is already there.

Key Takeaways

  • The open() function takes two pieces of information: the filename and the mode, which tells Python what you want to do with the file.
  • Read mode ("r") lets you view a file, write mode ("w") creates or overwrites a file, and append mode ("a") adds to the end of an existing file.
  • Always close a file when you are done with it by calling file.close(), or use a with statement to close it automatically.
  • If the file is not in the same folder as your Python script, you need to give the full path to where it lives on your computer.

Why you need to close files

When you open a file, Python sets aside memory and resources to work with it. If you do not close it, those resources stay tied up and your program can slow down or run into problems. Closing the file tells Python you are done and it can free up that space.

The safest way to handle this is to use a with statement, which closes the file automatically even if something goes wrong:

with open("myfile.txt", "r") as file: content = file.read()

Inside the with block, you can read, write, or do whatever you need. Once you leave that block, Python closes the file for you. This is the method most Python programmers use because it is harder to accidentally leave a file open.

Reading from a file

Once a file is open, you have three main ways to read what is inside. The read() method pulls in the entire file as one long string. The readline() method pulls in one line at a time. The readlines() method pulls in all lines as a list.

If your file has 100 lines and you only need the first few, readline() is more efficient because it does not load the whole thing into memory. If you need to work with each line separately, readlines() gives you a list you can loop through:

with open("myfile.txt", "r") as file: for line in file.readlines(): print(line)

This prints each line one at a time. You can also loop directly over the file object without calling readlines(), which is even more efficient for large files.

Writing and appending to files

Write mode ("w") creates a brand new file or completely replaces an existing one. If you open a file that already has content and use write mode, that content disappears. Append mode ("a") adds to the end instead:

with open("myfile.txt", "w") as file: file.write("This is new content.")

The write() method puts text into the file. If you want to write multiple lines, you need to include the line break character \n yourself:

with open("myfile.txt", "a") as file: file.write("Line one.\n") file.write("Line two.\n")

This adds two new lines to the end of the file without erasing what was there before.

Finding files in different folders

If the file you want to open is not in the same folder as your Python script, you need to tell Python where to find it. You do this by giving the full path to the file:

file = open("/Users/yourname/Documents/myfile.txt", "r")

On Windows, the path looks slightly different because it uses backslashes:

file = open("C:\\Users\\yourname\\Documents\\myfile.txt", "r")

A safer way is to use the pathlib module, which handles these differences automatically and is easier to read:

from pathlib import Path file_path = Path("Documents") / "myfile.txt" with open(file_path, "r") as file: content = file.read()

Handling errors when files do not exist

If you try to open a file that does not exist, Python stops and shows an error. You can prevent this by using a try and except block, which tells Python what to do if something goes wrong:

try: with open("myfile.txt", "r") as file: content = file.read() except FileNotFoundError: print("The file does not exist.")

This way, if the file is not there, your program prints a message instead of crashing. You can also check whether a file exists before you try to open it using the pathlib module:

from pathlib import Path file_path = Path("myfile.txt") if file_path.exists(): with open(file_path, "r") as file: content = file.read()

Working with different file types

The open() function works the same way for any file type — text files, CSV files, JSON files, and others. The difference is in how you read and understand the content after you open it.

For plain text files, read() gives you the raw text. For CSV files (spreadsheet data separated by commas), you usually use the csv module to parse it properly. For JSON files (structured data), you use the json module. These modules handle the formatting so you do not have to:

import json with open("data.json", "r") as file: data = json.load(file)

The json.load() function reads the file and converts it into a Python dictionary or list you can work with directly.

Frequently Asked Questions

What is the difference between read mode and append mode?

Read mode ("r") lets you look at a file but not change it. Append mode ("a") lets you add new content to the end of a file without erasing what is already there. Write mode ("w") creates a new file or completely replaces an existing one.

Do I have to use a with statement, or can I just call close()?

You can call close() directly, but a with statement is safer because it closes the file automatically even if your code has an error. If you forget to call close(), the file stays open and wastes memory.

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

Python shows a FileNotFoundError and stops running your code. You can prevent this by using a try and except block, or by checking if the file exists first using Path.exists().

How do I open a file from a different folder?

Give the full path to the file instead of just the filename. On Windows, use backslashes like C:\\Users\\name\\file.txt. On Mac or Linux, use forward slashes like /Users/name/file.txt. The pathlib module handles these differences automatically.

Can I read and write to the same file at the same time?

Not with the standard open() function. You can use read-write mode ("r+") to both read and write, but you have to be careful about where the cursor is in the file. For most tasks, it is simpler to read the file, make your changes in memory, and then write it back out.