Opening and Reading Files in Python
Opening and Reading Files
Reading data from files is one of the most common tasks in programming: loading configuration settings, processing log files, importing records from text exports, or reading user-provided content.
Python reads files with the built-in open() function, which returns a file object. The file object provides several methods for reading data — all at once, a few characters at a time, or line by line.
Files can be opened from the same directory as your Python script, or from any other location by using a file path.
The Example File
All examples in this lesson use a text file named sample.txt, stored in the same directory as the Python program. It contains three lines:
Hello there!
This file is created to demonstrate file reading.
Have a great day!
Reading the Entire File With read()
The read() method returns the entire content of the file as a single string.
file_data = open("sample.txt", "r")
print(file_data.read())
file_data.close()
Expected output:
Hello there!
This file is created to demonstrate file reading.
Have a great day!
What happens:
open("sample.txt", "r")opens the file in read mode.file_data.read()loads the complete content into memory as one string, including the line breaks.file_data.close()closes the file.
read() is convenient for small files. For very large files — such as log files that are hundreds of megabytes — loading everything at once can use a lot of memory. Reading line by line, shown later in this lesson, is better for those.
Opening Files From Another Location
If the file is not in the current directory, provide its path.
Example: Reading a File With an Absolute Path
file_data = open("C:/data/files/message.txt", "r")
print(file_data.read())
file_data.close()
This opens message.txt from the folder C:/data/files/ on a Windows computer. On Linux or macOS, an absolute path looks like /home/asha/data/message.txt.
Path tips:
- Forward slashes (
/) work on all operating systems, including Windows. - If you use backslashes on Windows, use a raw string:
r"C:\data\files\message.txt". Otherwise, sequences such as\fwould be treated as escape characters. - A relative path, such as
"data/message.txt", is resolved from the current working directory — usually the folder from which you ran the program.
Using the with Statement (Best Practice)
The with statement opens a file and closes it automatically when the indented block ends — even if an error occurs inside the block.
with open("sample.txt", "r") as file_data:
print(file_data.read())
Expected output:
Hello there!
This file is created to demonstrate file reading.
Have a great day!
- There is no need to call
close()manually. - The code is cleaner and safer, because the file can never be accidentally left open.
The remaining examples use the with statement.
Closing Files Manually
If you do not use with, you must close the file yourself with close().
file_data = open("sample.txt", "r")
print(file_data.readline())
file_data.close()
Expected output:
Hello there!
The extra blank line is explained in the readline() section below.
Leaving files open can waste system resources and, when writing, can cause data loss. If an error occurs between open() and close(), the close() line never runs — another reason the with statement is preferred.
Reading Part of a File
read() accepts an optional number that limits how many characters are returned.
Example: Reading the First 8 Characters
with open("sample.txt", "r") as file_data:
print(file_data.read(8))
Expected output:
Hello th
The first eight characters are H, e, l, l, o, a space, t, and h.
The File Position
A file object remembers its current position. Each read continues from where the previous one stopped:
with open("sample.txt", "r") as file_data:
print(file_data.read(5))
print(file_data.read(6))
Expected output:
Hello
there
The first call reads Hello; the second continues from position 5, reading a space followed by there. This position tracking also applies to readline() and to loops over the file.
Reading Files Line by Line
Reading a Single Line With readline()
readline() reads one line, up to and including the newline character at its end.
with open("sample.txt", "r") as file_data:
print(file_data.readline())
Expected output:
Hello there!
Why is there a blank line? The line returned by readline() is "Hello there!\n" — it already ends with a newline character. print() then adds its own newline, producing an empty line after the text. You can avoid this with print(line, end="") or by removing the newline with strip().
Reading Multiple Lines
Each call to readline() continues from where the previous call stopped.
with open("sample.txt", "r") as file_data:
print(file_data.readline())
print(file_data.readline())
Expected output:
Hello there!
This file is created to demonstrate file reading.
The first call reads line 1, and the second reads line 2. When the end of the file is reached, readline() returns an empty string "".
Reading All Lines Into a List With readlines()
readlines() returns a list, with each line as a separate string.
with open("sample.txt", "r") as file_data:
lines = file_data.readlines()
print(lines)
print(len(lines))
Expected output:
['Hello there!\n', 'This file is created to demonstrate file reading.\n', 'Have a great day!']
3
Each line keeps its \n, except the last line, because the file does not end with a newline. Like read(), readlines() loads the whole file into memory.
Looping Through All Lines
The most efficient way to process a file line by line is to loop over the file object directly.
with open("sample.txt", "r") as file_data:
for line in file_data:
print(line.strip())
Expected output:
Hello there!
This file is created to demonstrate file reading.
Have a great day!
Why this approach is preferred:
- Memory-friendly — only one line is held in memory at a time, so it works even for very large files.
- Simple — a file object is iterable, just like a list.
line.strip()removes the newline (and any surrounding spaces), so no blank lines appear.
Comparing the Reading Methods
| Method | Returns | Reads | Best For |
|---|---|---|---|
read() | One string | The whole file | Small files |
read(n) | One string | Up to n characters | Reading fixed-size chunks |
readline() | One string | One line | Reading a header or a few lines |
readlines() | A list of strings | The whole file | Small files you need as a list |
for line in file | One line per loop iteration | Line by line | Large files and most line processing |
Practical Example: Counting Lines and Words
line_count = 0
word_count = 0
with open("sample.txt", "r", encoding="utf-8") as file_data:
for line in file_data:
line_count += 1
word_count += len(line.split())
print("Lines:", line_count)
print("Words:", word_count)
Expected output:
Lines: 3
Words: 14
- Each loop iteration processes one line.
line.split()breaks the line into words, andlen()counts them: 2 + 8 + 4 = 14.encoding="utf-8"ensures the file is decoded the same way on every operating system.
Common Mistakes
| Mistake | Problem |
|---|---|
| The file is not in the current working directory | FileNotFoundError; check the path or the folder you run from |
Calling read() twice | The second call returns "" because the position is already at the end |
Forgetting that lines end with \n | Extra blank lines when printing; use strip() |
Using read() on very large files | High memory use; loop over the file instead |
| Reading after the file is closed | ValueError: I/O operation on closed file |
| Unescaped backslashes in Windows paths | Escape characters corrupt the path; use / or a raw string |
Related Concepts
- Python File Handling — file modes and the
open()function - Python Writing and Creating Files — saving data to files
- Python Strings —
strip()andsplit()for processing lines - Python Exception Handling — handling a missing file