Read text file line by line in Python

Python read text file line by line

In this post, we will see how to read text file line by line in Python.

To understand file operation, let’s first understand, what is the file? A file is an external storage on hard drive, where data can be stored and regained, if required.

In python, we can work with different files like excel, pdf, csv, text etc. To access different files, we have to use different library modules of python but to access text file, we don’t need to use any library module of python. In this blog, we will talk about how to use text file in python, how to access text file, how to read, create text file etc.

In python, to do file operation on text file, we need to first access the file by using of different access mode of text file.

Python supports 6 access modes to read and write text file as read mode, write mode, read+ write mode, write + read mode, append mode and append + read mode. We can use access mode for normal text file and binary text file. For binary mode, we use b after access mode symbol like for read file; access mode symbol is r so for binary text file we use rb. Let’s understand more about access modes.

Name Symbol Description
read r,rb This file mode opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
write w,wb This file mode opens a file for writing only. It overwrites the file; if the file exists otherwise file object creates a new file for writing.
append a,ab It opens a file for appending in the append mode. The file pointer is put at the end of the file; if the file exists otherwise file object creates a new file for writing.
read+write r+,rb+ This file mode opens a file for both reading and writing. The file pointer placed at the beginning of the file.
write+read w+,wb+ It opens a file for both writing and reading. It overwrites the existing file; if the file exists otherwise file object creates a new file for reading and writing.
append+read a+,ab+ It opens a file for both appending and reading in the append mode. The file pointer is placed at the end of the file, if the file exists otherwise file object creates a new file for reading and writing.

Attributes of File Object

Python supports following attributes of file object, which tells about file like is file close, file name and file mode.

Attributes Description
file_object.closed It returns true, if the file is closed otherwise it returns false.
file_object.mode It returns access mode in which file is being opened like w,r,a etc..
file_object.name It returns the name of the file.
file_object.tell() It is used to get the exact position of mouse pointer in the file.
Seek(Offset[,From]) It changes the current file position. Here, Offset= It indicates the number of bytes to be moved. From= It specifies the reference position where the bytes are to be moved. If From=0 means beginning position of the file If From=1 means current position of the file If From=2 means end position of the file
Operations on Text file
The operations of text file work with file object. Let’s first see the steps of file operation as below.
1) Open file
2) Do read or write operation
3) Close file

Python supports following operations.

Open a File

To open a file, python use built in function as open(), which returns a file object. We can’t do any operation without opening the file. So this is the first step of file operation.
Syntax:

  • File_path: It is the name of the file or path of the file, which we want to open.
  • Access_mode: It is the access mode in which file is to be opened like read, write etc. Default access mode is read (r)
  • buffering: It is a temporary space.
    • If the buffering value is set to 0 means no buffering takes place.
    • If the buffering value is set to 1 means line buffering is performed while accessing a file.
    • If we specify the buffering value greater than 1, then buffering action is performed with the indicated buffer size.
    • If we specify the buffering value as a negative, then the buffer size is the system default (default behavior).

Let’s open a filetest.text file in read mode.
First we need to create a text file with path as C:\Users\admin\Desktop\filetest.text and practice python file with path as C:\Users\admin\Desktop\example.py. Always remember that we have to keep both the files at same path.

Let’s write code as below in example.py file.
Input code:

Output:
After executing the "example.py" file, output shows as below with file name and access mode name.

Opened file name: <_io.TextIOWrapper name=’filetest.txt’ mode=’r’ encoding=’cp1252′>

Let’s open the same file with its full path address in read mode in python shell by writing below code to understand the result.

Output:

Opened file name with path: C://Users//admin//Desktop//filetest.txt

If file is not created, then we can create the new file by using open() method with write(w) access mode.
Let’s create new pythonfile.txt at desktop by using below code in example.py file.

In the above example, file_open is the file object.
Here, we used (w) access mode because w is used to write text in existing file or in new file, which created by ‘w’ access mode, if file is not exist
Output:
After executing the example.py file, output shows as below with file name and access mode name and blank new file as pythonfile.txt would be created at desktop.

Opened file name: <_io.TextIOWrapper name=’pythontest.txt’ mode=’w’ encoding=’cp1252′>

Read data from a File line by line

Python use built in function as read() to read all text data from existing text file.
Syntax:

Here, value is the number of bytes to be read. In case, no value is given it reads till end of file is reached.
Let’s read ‘pythonfile.txt’ file by writing below code.

Input Code:

In the above example, we read all the lines of file.

Output:

Read data of file: John got 75%.
Sam got 80%.
Rick got 65%.

Let’s read only first 7 character bytes of ‘pythonfile.txt’ file by writing below code.
Input Code:

In the above example, we have used read() function with value as 7 so output shows as ‘John go’ as the 7 character of first line as John got 75% of file.

Python supports 2 reading line method as below.

readline() method

It returns the line of the file. This is all text up to end and including the next newline character.

Syntax:

where byte_size is same like read() method

Output:

John got 75%.
Sam got 80%.

In the above example, by using of readline() method, we have printed first two lines. We can use for loop also for printing same lines as below.

Output:

John got 75%.
Sam got 80%.

Let’s read 5 bytes of first line by using below code.
Input Code:

readlines() method:

It returns a list of the lines of the file. Each list item is a single line including the newline characters.

Syntax:

where byte_size is same like read() method
Let’s read all lines of ‘pythonfile.txt’ file by using readlines() method .
Input Code:

In the above example by using readlies() method, we created list of all lines of file.
Output:

[‘John got 75%.\n’, ‘Sam got 80%.\n’, ‘Rick got 65%.’]

Let’s read 5 bytes of same existing file by using below code.
Input Code:

Output:

[‘John got 75%.\n’]

In the above example, output shows first element of all the lines of list because first element includes 5 bytes as John
Let’s take an example of finding position of mouse cursor in the file by using tell() and seek() method.

Output:

Read file: John got 75%.
Current file position: 13
Change file position as beginning of file: 0
Again read file: John got

In the above example, by using seek(0,0) method, we moved mouse cursor at beginning of the file or zero byte position and by using of tell () method, we displayed the current position of mouse cursor. After using read () method, we read first 13 bytes of the file as John got 75% so the position of cursor is 13 and then we change the position of cursor as 0 so second time cursor display 8 bytes from the beginning of the file so result is John got.

Append data into File

By using of append (a) access mode, we can append data into existing write file at the end of the file.
Syntax:

Let’s write Swan got 65%. in ‘pythonfile.txt’ file by using append mode and writing below code.
Input file:
Input file for writing in python
Input Code:

Output:
Append text to file in Python
After executing above code, data Swan got 65%. is added at the end of the file.

Write data into a file:

Python use built in function as write() to write any text and binary data into text file.
The write() method does not add a newline character('\n') to the end of the string.
Syntax:

Let’s write This is test file and Learn python from Java2Blog.com in blank pythonfile.txt file by writing below code. We can use ‘\n’ escape character for next line.
Input code:

Output: pythonfile.txt with text data.
Write to file in Python
Let’s see example of writing variable values in the same file by writing below code.
Input code:

In the above example, we have created two variables as name and result and then by using for loop and write () method add the variable data into existing file.
Output: Existing pythonfile.txt file with overwritten text data.
Write to a file

Note: The w access mode overwrites the data of existing file.

Close a File

Python use built in function as close() to close opened file.

Once we are finished with the operations on an opened file at the end we need to close the file. It is done by the close () method.
Syntax:

Let’s close opened pythonfile.txt by using below code and write the file attributes. This command is close file in virtual machine language form but not physically.
Input code:

Output:

Opened file name: pythonfile.txt
Opened file access mode: r
Is file closed? True

This function is used to prevent the file data from destroy. Always remember that we have to always close file physically and virtually, when we use writing operation otherwise it will not work on physical open file.

That’s all about how to read text file line by line in Python.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *