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.
Table of Contents
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.
Further reading:
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 |
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:
1 2 3 |
file_ object=open (file_path , access_mode , buffering) |
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).
- If the buffering value is set to
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:
1 2 3 4 |
file_open =open("filetest.txt","r") print("Opened file name: ",file_open) |
Output:
After executing the "example.py" file, output shows as below with file name and access mode name.
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.
1 2 3 4 5 |
file_open=open("C://Users//admin//Desktop//filetest.txt","r") print("Opened file name with path: ", file_open.name) Here, we have used "file_object.name " method to know the path of the file. |
Output:
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.
1 2 3 4 |
file_open =open("pythonfile.txt","r") print("Opened file name: ",file_open). |
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.
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:
1 2 3 |
file_object.read(value) |
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:
1 2 3 4 5 |
file_open =open("pythonfile.txt","r") print('Read data of file: ', file_open.read()) file_open.close() |
In the above example, we read all the lines of file.
Output:
Sam got 80%.
Rick got 65%.
Let’s read only first 7 character bytes of ‘pythonfile.txt’ file by writing below code.
Input Code:
1 2 3 4 5 |
file_open =open("pythonfile.txt","r") print('Read data of file: ', file_open.read(7)) file_open.close() |
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:
1 2 3 |
file_object.readline(byte_size) |
where byte_size
is same like read()
method
1 2 3 4 5 6 |
file_open =open("pythonfile.txt","r") print(file_open.readline()) print(file_open.readline()) file_open.close() |
Output:
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.
1 2 3 4 5 6 |
file_open =open("pythonfile.txt","r") for i in range(2): print(file_open.readline()) file_open.close() |
Output:
Sam got 80%.
Let’s read 5 bytes of first line by using below code.
Input Code:
1 2 3 4 5 |
file_open =open("pythonfile.txt","r") print(file_open.readline(5)) file_open.close() |
readlines() method:
It returns a list of the lines of the file. Each list item is a single line including the newline characters.
Syntax:
1 2 3 |
file_object.readlines(byte_size) |
where byte_size
is same like read()
method
Let’s read all lines of ‘pythonfile.txt’ file by using readlines() method .
Input Code:
1 2 3 4 5 |
file_open =open("pythonfile.txt","r") print(file_open.readlines()) file_open.close() |
In the above example by using readlies() method, we created list of all lines of file.
Output:
Let’s read 5 bytes of same existing file by using below code.
Input Code:
1 2 3 4 5 |
file_open =open("pythonfile.txt","r") print(file_open.readlines(5)) file_open.close() |
Output:
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.
1 2 3 4 5 6 7 8 9 10 |
file_open =open("pythonfile.txt","r") print('Read file: ', file_open.read(13)) cursor_position=file_open.tell() print('Current file position: ',cursor_position) change_position=file_open.seek(0,0) print('Change file position as beginning of file: ',change_position) print('Again read file:',file_open.read(8)) file_open.close() |
Output:
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:
1 2 3 |
file_object=open(file_path, 'a') |
Let’s write Swan got 65%.
in ‘pythonfile.txt’ file by using append mode and writing below code.
Input file:
Input Code:
1 2 3 4 5 |
file_open =open("pythonfile.txt","a") file_open.write('\nSwan got 65%.') file_open.close() |
Output:
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:
1 2 3 |
file_object.write(string) |
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:
1 2 3 4 5 6 |
file_open =open("pythonfile.txt","w") file_open.write('This is test file') file_open.write("Learn python from Java2Blog.com") file_open.close() |
Output: pythonfile.txt
with text data.
Let’s see example of writing variable values in the same file by writing below code.
Input code:
1 2 3 4 5 6 7 8 |
file_open =open("pythonfile.txt","w") name=['John','Sam','Rick'] result=[75,80,65] for i in range(len(name)): file_open.write('\n'+name[i]+' got '+str(result[i])+'%.') file_open.close() |
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.
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:
1 2 3 |
file_object.close() |
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:
1 2 3 4 5 6 7 |
file_open =open("pythonfile.txt","r") print("Opened file name: ",file_open.name) print("Opened file access mode: ",file_open.mode) file_open.close() print("Is file closed? ",file_open.closed) |
Output:
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.