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.
  1. with - file object is automatically closed after exiting from with execution block.
    (exception handling inside the with block)

  2. for line in f - memory for loop iterates through the f file object line by line.
Internally it does buffered IO (to optimized on costly IO operations) and memory management .

How to read a file line-by-line into a list?


read line by line

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.


Python File Open

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.
python FileNotFoundError exception
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")