Python Read File

File handling is used to read a file in python. It is one of the important concepts in python. It is required most oftenly in developing a web application.

Opening a File

To read a file, it must be opened. To open a file in Python open() function is used. open() function takes two parameters filename and mode.

Here filename is the name of the file to open and mode specify the mode (for reading, writing, appending etc.) in which you want to open a file.

Syntax of open() function in python

If you want to open a file for reading then specifying mode is not necessary.
f = open("demoFile.txt")
You can also explicitly specify that you want to open text file demoFile.txt for reading.
f = open("demoFile.txt", "rt")
Here r specify that you want to open demoFile.txt for reading and t specifies that it is a text file.

Python File Opening Modes

There are 4 different file opening modes available in Python.
  1. "r" - This is the default mode. This is used for reading a file. If the file does not exist an error is thrown.
  2. "w" - This mode is used for writing to a file. If the file does not exist , it is created.
  3. "a" - This mode is use for appending data to the end of the file. File is created if it does not exist.
  4. "x" - This mode is used for creating the file specified. An error is thrown if the file already exists.
You can also specify how you file should be handled like in text mode or binary mode.

For this there are two additional modes that we can specify with above modes (like the one we specified in the Syntax "rt").
  1. t - This is the deafult text mode.
  2. b - Binary mode.

Python Read File Line by Line into List

To read a file line by line in python we can use readines() method. readines() reads all the lines in a file at once and returns a list of lines.
f = open("demoFile.txt","r")

list = f.readlines()

f.close()
Note : Each line in the list contains a newline (\n) character at the end.

Python read file - one line at a time

readlines() is useful when we have small size file. However if we have a larger file this method is not memory efficient. To overcome this we can read one line at a time.

We can read a file by reading one line at a time by using readline() method and while loop.
f = open("demoFile.txt","r")

list = []
line = f.readline()

while line:
	
	list.append(line)
	line = f.readline()

f.close()

Python Read File into a String

To read a file into a string variable we can use read() method in python. read() method returns all the file bytes in the form of string.
f = open("demoFile.txt", "rt")

print(f.read())

Python Read File Skip Lines

To skip some lines while reading a file we can use the concept of slicing a list. Let's say we need to skip first 10 lines of our demoFile.txt, following code can do this for us.
f = open("demoFile.txt","r")

list = f.readlines()[10:]

f.close()
We can also skip any lines in between a file with slicing.

Read more about the concept of slicing lists in python.

Python Read Files from Directory

os.listdir() lists all the content of a directory including files and other directories. To extract the files out of it we can use a filter like one below.
from os import list dir
from os.path import isfile, join

#set my path to desired directory
my path = "/home/python/files"

fileNames = [f for f in listdir(mypath) if isfile(join(mypath, f))]

# now that you have got fileNames you can read the required

Python Read File Word by Word

To get all the words in a file we can use split() method.
f = open("demoFile.txt", "rt")
	words = [word for line in f for word in line.split()]

Python Read File Character by Character

To read a file character by character read() method can be used with with size parameter specified.
with open("demoFile.txt","r") as f:
	while True:
		ch = f.read(1)
		if not ch:
			print("End of file")
			break
		print(ch)