How Python Reads a File
The idea
You have a file on your computer. Python needs to find it, open it, and read what's inside.
Three methods. One pattern. All the same with open() block.
Where to put your file
Python looks for files relative to where your script is located.
The simplest setup: put the file in the same folder as your .py script.
project/
script.py
soldiers.txt
Then you open it like this:
with open("soldiers.txt", "r") as f:
...
If the file is in a subfolder:
with open("data/soldiers.txt", "r") as f:
...
If Python can't find the file, you get a FileNotFoundError. That almost always means the path is wrong — check the folder, check the filename, check the extension.
The file for this lesson
Download soldiers.txt and place it in the same folder as your script before running any of the examples below.
read() — the whole file at once
with open("soldiers.txt", "r") as f:
content = f.read()
print(content)
Returns the entire file as one string — newlines included.
Good for small files. Not ideal for large ones — the whole thing loads into memory at once.
readlines() — all lines as a list
with open("soldiers.txt", "r") as f:
lines = f.readlines()
print(lines)
Output → ['Raven\n', 'Wolf\n', 'Ghost\n', 'Viper\n', 'Bull\n']
Each line becomes an element. The \n at the end is the newline character — strip it when you need clean values:
with open("soldiers.txt", "r") as f:
lines = [line.strip() for line in f.readlines()]
print(lines)
Output → ['Raven', 'Wolf', 'Ghost', 'Viper', 'Bull']
readline() — one line at a time
with open("soldiers.txt", "r") as f:
first = f.readline()
second = f.readline()
print(first.strip())
print(second.strip())
Each call moves to the next line. Useful when you only need the first few lines of a large file.
Looping directly over the file — most common
with open("soldiers.txt", "r") as f:
for line in f:
print(line.strip())
Output:
Raven
Wolf
Ghost
Viper
Bull
Python reads the file line by line without loading it all into memory. This is the pattern you'll use most.
Handling a missing file
If the file might not exist, wrap it in a try/except:
try:
with open("soldiers.txt", "r") as f:
for line in f:
print(line.strip())
except FileNotFoundError:
print("File not found. Check the path.")
Heads up!
- Always use
encoding="utf-8"if your file contains special characters readlines()keeps the\n— use.strip()to clean itread()on a large file loads everything into memory at once — use a loop instead- The file path is relative to where you run the script — not where the script file is saved
What you should understand now
- Put the file in the same folder as your script for the simplest setup
read()returns the whole file as a stringreadlines()returns all lines as a list — with\nincludedreadline()reads one line at a time- Looping directly over the file is the most memory-efficient pattern
- Use
try/except FileNotFoundErrorwhen the file might not exist