The Three Ways to Read a File Into Python
To import a file in Python, you use the open() function to read it, then store the contents in a variable. The simplest version takes two pieces of information: the file name and how you want to read it. Python then loads that file into memory so your code can work with it.
The three main approaches are reading the entire file at once, reading it line by line, or using a context manager (which is the safest method). Which one you use depends on how large your file is and what you plan to do with the data.
Key Takeaways
- The open() function is the standard way to import a file, and you must tell it both the file name and the read mode (usually "r" for read).
- Use read() to load the entire file into one variable, readlines() to get a list of lines, or loop through the file directly to process it line by line.
- Always use a with statement when opening files, because it automatically closes the file when you are done, even if your code crashes.
- The file path must be correct — use the full path if the file is not in the same folder as your Python script, or use forward slashes even on Windows.
- Text files and CSV files use mode "r", but binary files like images use mode "rb".
Reading an Entire File at Once
If your file is small enough to fit in memory, you can read the whole thing into a single variable using the read() method. This is the fastest way if you need all the data at once.
Here is the basic structure:
with open("myfile.txt", "r") as file: content = file.read() print(content)
The with statement opens the file, runs your code, and then closes the file automatically. The "r" means read mode. After this runs, the variable content holds the entire file as a single string, including all line breaks.
If your file is very large (hundreds of megabytes or more), this method will slow down your computer because Python has to hold all of it in memory at once. For large files, use the line-by-line approach instead.
Reading a File Line by Line
When you need to process a file without loading all of it into memory, loop through it one line at a time. This is much faster for large files and is the method most Python programmers use.
with open("myfile.txt", "r") as file: for line in file: print(line.strip())
This code opens the file and then repeats the code inside the loop once for each line. The strip() method removes the newline character at the end of each line so your output looks clean. Without it, you will see extra blank lines between each line of text.
You can also use readlines() to get a list of all lines at once, which is useful if you need to access a specific line by its number:
with open("myfile.txt", "r") as file: lines = file.readlines() print(lines[0])
This loads all lines into a list called lines, and then lines[0] gives you the first line. Remember that Python counts from zero, so the first line is always at position 0.
Importing CSV Files and Structured Data
If your file contains data in columns (like a spreadsheet), use Python's csv module instead of reading it as plain text. This module understands that commas separate the columns and handles the structure for you.
import csv with open("data.csv", "r") as file: reader = csv.reader(file) for row in reader: print(row)
The csv.reader() function takes your file and splits each line into a list of values. Each row is a list, so row[0] is the first column, row[1] is the second column, and so on.
If your CSV file has a header row with column names, use csv.DictReader() instead. This lets you access columns by name rather than by number:
import csv with open("data.csv", "r") as file: reader = csv.DictReader(file) for row in reader: print(row["Name"], row["Age"])
Now each row is a dictionary, and you can use the column name as the key to get the value you want.
Fixing the Most Common File Path Mistakes
The most common error when importing a file is that Python cannot find it. This happens when the file path is wrong. Python looks for the file relative to where your Python script is located, unless you give it a full path.
If your file is in the same folder as your Python script, just use the file name:
open("myfile.txt", "r")
If your file is in a subfolder called data, use a forward slash (even on Windows):
open("data/myfile.txt", "r")
If your file is in a parent folder (one level up), use two dots:
open("../myfile.txt", "r")
If you want to use the full path on your computer, start with the drive letter on Windows or a forward slash on Mac and Linux:
open("C:/Users/YourName/Documents/myfile.txt", "r") # Windows open("/Users/YourName/Documents/myfile.txt", "r") # Mac
Always use forward slashes in Python, even on Windows. Python will convert them automatically. If you use backslashes, Python treats them as escape characters and your path will break.
Handling Errors When a File Does Not Exist
If Python cannot find your file, it raises a FileNotFoundError. You can catch this error and handle it gracefully instead of letting your program crash:
try: with open("myfile.txt", "r") as file: content = file.read() except FileNotFoundError: print("The file was not found. Check the file name and path.")
The try block contains the code that might fail. If it does, the except block runs instead. This way your program does not crash — it prints a message and continues.
You can also check whether a file exists before trying to open it, using the os module:
import os if os.path.exists("myfile.txt"): with open("myfile.txt", "r") as file: content = file.read() else: print("File not found")
This checks whether the file exists before you try to open it, which prevents the error from happening in the first place.
Frequently Asked Questions
What is the difference between "r" and "rb" mode?
"r" reads a text file as strings that you can print and edit. "rb" reads a binary file (like an image or PDF) as raw bytes. Use "r" for text files, CSV files, and code files. Use "rb" for images, videos, and other non-text files.
Do I have to close the file after reading it?
No, not if you use a with statement. The with statement closes the file automatically when the block ends. If you use open() without with, you must call file.close() when you are done, or the file will stay open and waste memory.
Can I import a file from the internet?
Yes, but you need the urllib module instead of open(). Use urllib.request.urlopen() to download a file from a URL, then read it the same way you would read a local file.
What if my file uses a different character encoding?
Most files use UTF-8 encoding, which Python assumes by default. If your file uses a different encoding (like Latin-1 or Windows-1252), add the encoding parameter: open("myfile.txt", "r", encoding="latin-1"). Check your file's properties or documentation to find out which encoding it uses.
How do I import a JSON file?
Use the json module. Open the file in read mode, then use json.load() to convert it into a Python dictionary or list: data = json.load(file). This is faster and safer than reading it as text and trying to parse it yourself.