Read a File Line-by-Line in Python
Assume you have the "sample.txt" file located in the same folder:
with open("sample.txt") as f:
for line in f:
print(line)
The above code is the correct, fully Pythonic way to read a file.
- with - file object is automatically closed after exiting from with execution block.
(exception handling inside the with block)
- for line in f - memory for loop iterates through the f file object line by line.
How to read a file line-by-line into a list?

readlines()
The Python readlines() method takes a text file as input and stores each line in the file as a separate element in a list.
fOpen = open("sample.txt",'r')
myList = fOpen.readlines()
print(myList)
Python readlines() with a parameter
fOpen = open("sample.txt",'r')
myList = fOpen.readlines(10)
print(myList)
The above program do not return the next line if the total number of returned bytes ar more than 10 because this time with the parameter set to 10 bytes in readlines() .
How to read a large file - line by line?
In the case you are working with Big Data using readlines() is not very efficient as it can result in MemoryError because this function loads the entire file into memory, then iterates over it. A slightly better approach for large files is to use the fileinput module , as follows:
import fileinput
for line in fileinput.input(['sample.txt']):
print(line)
The fileinput.input() call reads lines sequentially, but doesn't keep them in memory after they've been read or even simply so this, since file in Python is iterable.
Read file line by line into array in Python
Following program read the content of the file and add into an Array.
myArray = []
with open("sample.txt") as f:
myArray = f.readlines()
print(myArray)
Python open() Function
The open() function opens a file, and returns it as a file object. The open() function takes in multiple arguments . Syntax
open(file, mode(optional))
file - file system path.
mode(optional) - define which mode you want to open the file.

FileNotFoundError exception
If the file is not found in the specified path, it raises the FileNotFoundError exception. FileNotFoundError is a subclass of OSError , catch that or the exception itself.
You can use try/except to handle this exception.
try:
with open("unknown.txt") as f:
for line in f:
print(line)
except FileNotFoundError as not_found:
print("Wrong file or file path")
Related Topics
- How to open and close a file in Python
- How to write files in python
- How to read a file properly in Python
- How to use Split in Python
- Directory Operations Using Python
- How to check that a file or directory exists with Python
- File Access Mode in Python
- Difference between read, readline and readlines | python
- Python file positions | seek() and tell()
- How to Copy a File using Python