Working with Files - Reading
Learn to read data from text files in Python
Working with Files - Reading
Why Read Files?
Programs often need to work with data stored in files. Think about reading a list of names from a text file, loading configuration settings, or processing a data file.
Reading files lets your program access information that was saved earlier or created by other programs.
Common uses:
- Read configuration settings
- Load user data
- Process text documents
- Read CSV data files
- Load saved game progress
Opening a File
To read a file, you first need to open it using the open() function.
file = open("data.txt", "r")What this does: Opens data.txt file in read mode. The "r" means read-only.
Important: Always close the file when done.
file.close()Reading Entire File
The easiest way to read a file is using the read() method.
file = open("data.txt", "r")
content = file.read()
print(content)
file.close()What happens: Reads everything from the file and stores it in the content variable as one big string.
Better Way - Using with Statement
The with statement automatically closes the file, even if something goes wrong.
with open("data.txt", "r") as file:
content = file.read()
print(content)Why this is better:
- No need to remember file.close()
- File closes automatically when done
- File closes even if there's an error
- This is the recommended way
From now on, we'll use with statement in all examples.
Reading Line by Line
Often you want to process one line at a time instead of reading everything.
Using readline()
with open("data.txt", "r") as file:
line1 = file.readline()
line2 = file.readline()
print(line1)
print(line2)What happens: Each readline() reads one line and moves to the next line.
Using readlines()
with open("data.txt", "r") as file:
lines = file.readlines()
print(lines)What this returns: A list where each item is one line from the file.
Example result: ['First line\n', 'Second line\n', 'Third line\n']
Notice: Each line includes \n (newline character) at the end.
Looping Through Lines
This is the most common and efficient way to read files.
with open("data.txt", "r") as file:
for line in file:
print(line)What happens: Reads one line at a time in the loop. Memory efficient for large files.
Cleaning Up Lines
Lines from files often have extra whitespace or newline characters. Use strip() to clean them.
with open("data.txt", "r") as file:
for line in file:
clean_line = line.strip()
print(clean_line)What strip() does: Removes whitespace (spaces, tabs, newlines) from both ends of the string.
Handling File Errors
What if the file doesn't exist? Your program will crash unless you handle the error.
try:
with open("data.txt", "r") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("File not found")What this does: If file doesn't exist, instead of crashing, it prints "File not found".
Reading Specific Number of Characters
You can read a specific number of characters instead of everything.
with open("data.txt", "r") as file:
first_10 = file.read(10)
print(first_10)What happens: Reads only the first 10 characters from the file.
Checking File Position
When you read from a file, Python keeps track of where you are.
with open("data.txt", "r") as file:
print(file.tell())
file.read(10)
print(file.tell())What tell() does: Shows current position in the file (number of characters read so far).
Moving Position
You can move to a specific position using seek().
with open("data.txt", "r") as file:
file.read(10)
file.seek(0)
content = file.read()
print(content)What this does:
- Reads 10 characters
- seek(0) moves back to the beginning
- Reads entire file from start
Reading Different Encodings
Sometimes files use different character encodings. UTF-8 is the most common.
with open("data.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)When you need this: Files with special characters or multiple languages.
Practice Example
The scenario: You have a file called students.txt with student names, one per line. You want to read and process them.
File content (students.txt):
John Smith
Sarah Johnson
Mike Brown
Emma Davis
Python program:
try:
with open("students.txt", "r") as file:
students = []
for line in file:
clean_name = line.strip()
students.append(clean_name)
print("Total students:", len(students))
print("First student:", students[0])
print("All students:")
for i, student in enumerate(students, 1):
print(str(i) + ".", student)
except FileNotFoundError:
print("Student file not found")What this program does:
- Opens students.txt safely with error handling
- Creates empty list for students
- Reads each line and removes extra whitespace
- Adds each cleaned name to list
- Prints total count
- Shows first student
- Lists all students with numbers
Reading CSV-like Data
If your file has comma-separated values, you can split each line.
File content (data.txt):
John,25,Engineer
Sarah,30,Doctor
Mike,28,Teacher
Python program:
with open("data.txt", "r") as file:
for line in file:
clean_line = line.strip()
parts = clean_line.split(",")
name = parts[0]
age = parts[1]
job = parts[2]
print("Name:", name, "Age:", age, "Job:", job)What split() does: Breaks the line at each comma, creating a list of parts.
Key Points to Remember
Use open() with "r" mode to read files. Always use with statement so files close automatically.
read() gets entire file, readline() gets one line, readlines() gets all lines as a list.
Loop through file directly with "for line in file" - this is memory efficient for large files.
Use strip() to remove extra whitespace and newline characters from lines.
Use try-except with FileNotFoundError to handle missing files gracefully without crashing.
Common Mistakes
Mistake 1: Forgetting to close file
file = open("data.txt", "r")
content = file.read()
# Forgot file.close()!Fix: Use with statement instead.
Mistake 2: Reading file twice
with open("data.txt", "r") as file:
content1 = file.read()
content2 = file.read() # This will be empty!After reading once, you're at the end. Use seek(0) to go back.
Mistake 3: Wrong file path
file = open("documents/data.txt", "r") # File might not be hereAlways check the file path is correct relative to your program.
Mistake 4: Not handling newlines
with open("data.txt", "r") as file:
for line in file:
print(line) # This has double spacing!Fix:
print(line.strip())What's Next?
Now you know how to read files. Next, you'll learn about writing files - creating new files, adding content, and updating existing files.