How to Read a File in Python
What you’ll build or solve
You’ll read text files in Python using the safest, most common patterns.
When this approach works best
Reading a file works well when you:
Learn Python on Mimo
- Load data from a text file, like a list of names, config values, or log output.
- Process large files without loading everything into memory at once.
- Clean or search text, like finding errors in a log or filtering lines that match a keyword.
Avoid this approach when your data is structured like JSON or CSV and you need reliable parsing. In those cases, use json or csv so you don’t reinvent parsing rules.
Prerequisites
- Python installed
- You know what a file and folder are on your computer
Step-by-step instructions
1) Open the file with a context manager
Use with open(...) so Python closes the file automatically.
withopen("notes.txt","r")asf:
text=f.read()
print(text)
2) Choose how you want to read the contents
Pick the reading method based on the file size and what you need.
Option A (most common): Read the whole file with read()
Best for small files.
withopen("notes.txt","r")asf:
text=f.read()
print(text)
Option B: Read line by line in a loop
Best for large files or streaming-style processing.
withopen("notes.txt","r")asf:
forlineinf:
print(line.strip())
Option C: Read all lines into a list with readlines()
Useful when you want random access to lines, but it loads everything into memory.
LUA
withopen("notes.txt","r")asf:
lines=f.readlines()
print(lines[0])
3) Specify encoding explicitly
Always set encoding when opening text files to avoid decode errors.
withopen("notes.txt","r",encoding="utf-8")asf:
text=f.read()
print(text)
What to look for: utf-8 works for most modern files. If you see UnicodeDecodeError, try a Windows-friendly encoding in Troubleshooting. For portable paths, see Example 4.
4) Handle missing files cleanly
If a file might not exist, catch the error and show a helpful message.
CSS
try:
withopen("notes.txt","r",encoding="utf-8")asf:
text=f.read()
print(text)
exceptFileNotFoundError:
print("Could not find notes.txt. Check the file name and folder.")
Examples you can copy
Example 1: Read a whole file and count characters
LUA
withopen("notes.txt","r",encoding="utf-8")asf:
text=f.read()
print(len(text))
Example 2: Read line by line and keep only non-empty lines
clean_lines= []
withopen("notes.txt","r",encoding="utf-8")asf:
forlineinf:
line=line.strip()
ifline:
clean_lines.append(line)
print(clean_lines)
Example 3: Search a log file for lines that contain a word
matches= []
withopen("app.log","r",encoding="utf-8")asf:
forlineinf:
if"ERROR"inline:
matches.append(line.rstrip())
print(matches[:5])
Example 4: Read a file next to your script with pathlib
This example uses pathlib to build a path that works even when you run the script from a different folder.
frompathlibimportPath
file_path=Path(__file__).with_name("data.txt")
withfile_path.open("r",encoding="utf-8")asf:
text=f.read()
print(text)
Common mistakes and how to fix them
Mistake 1: Forgetting the context manager
What you might do:
f=open("notes.txt","r")
text=f.read()
print(text)
Why it breaks: The file can stay open longer than you expect, which can cause locked files or bugs in longer scripts.
Correct approach:
withopen("notes.txt","r",encoding="utf-8")asf:
text=f.read()
print(text)
Mistake 2: Using the wrong working directory
What you might do:
LUA
withopen("notes.txt","r",encoding="utf-8")asf:
print(f.read())
…and then get FileNotFoundError.
Why it breaks: Python looks in the folder you run the script from, which might not be the folder where the file lives.
Correct approach:
frompathlibimportPath
file_path=Path(__file__).with_name("notes.txt")
withfile_path.open("r",encoding="utf-8")asf:
print(f.read())
Mistake 3: Not setting an encoding
What you might do:
LUA
withopen("notes.txt","r")asf:
print(f.read())
Why it breaks: Python uses a default encoding that may not match the file, causing UnicodeDecodeError or garbled text.
Correct approach:
LUA
withopen("notes.txt","r",encoding="utf-8")asf:
print(f.read())
Troubleshooting
If you see FileNotFoundError, check the folder you run the script from. Print it with:
LUA
importos
print(os.getcwd())
If you see UnicodeDecodeError, try a different encoding. On Windows, cp1252 is a common fallback:
LUA
withopen("notes.txt","r",encoding="cp1252")asf:
print(f.read())
If your output has blank lines, you may be printing lines that already end with \n. Use print(line.strip()) or print(line, end="").
If you get PermissionError, close the file in other apps or read from a location you have access to.
If your script works in one IDE but not in the terminal, your working directory differs. Use pathlib to anchor paths to your script.
Quick recap
- Open files with
with open(...)so they close automatically. - Use
read()for small files, or loop over the file for large files. - Set
encoding="utf-8"for text files. - Catch
FileNotFoundErrorwhen the file may be missing. - Use
pathlibwhen you need paths that work across folders.
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot