Python Read File Tutorial

Python provides different ways and methods in order to read files. Files can be read completely, character by character, line by line, part of a file, or into a list by using Python. In this tutorial we examine all of these files read ways and methods for Python.

Open File

In order to read a file, we should open it. A file can be opened with different access modes like read only , read and write , write only etc. For this tutorial, the most appropriate access mode is read only as we only want to read files and do not want to write or append anything. The read-only mode is expressed with the r character for the open() method. In the following example, we open the file named myfile.txt .

f = open("myfile.txt","r")

If the file is located differently than the current working directory we can specify the absolute or full path like below.

f = open("/home/ismail/myfile.txt","r")

If you are using Windows operating system the absolute or full path can be specified a bit differently where we should use escape sequences.

f = open("C:\\Users\ismail\\myfile.txt","r")

Read All File

The read() method of the file object is used to read all file content and return it as a string. In the following example we all content of the file named myfile.txt .

f = open("myfile.txt","r")

content = f.read()

Read File Character by Character

The read() method can be also used to read a file character by character. The read() method accepts the count of characters as the parameter. The syntax of reading a file character by character is like below.

f.read(COUNT)
  • COUNT is the character or byte count.

In the following example, we read the file named myfile.txt character by character using the for loop.

f = open("myfile.txt","r")

for x in range(10):
   character = f.read(1)
   print(character)

Read File Line by Line

Python file object provides the readline() method which reads a single line from the file. In every execution of the readline() method single line is read and returned and then the cursor is iterated to the next line. In the following example, we read a single line by using the for loop for 5 times.

f = open("myfile.txt","r")

for x in range(10):
   character = f.readline()
   print(character)

Read File Into A List

The readlines() method is used to read all lines and return a list where every line is an item in the list.

f = open("myfile.txt","r")

lines = f.readlines()

Close File

As the last step, we should close the file in order to prevent the next file-related operations and release the computer resources. The close() method is used to close the already open files.

f.close()

Leave a Comment