How to read a text file in Selenium with python?


We can read a text file in Selenium with python by first creating a txt file and having a content on it.

First of all, we need to open the file and mention the path of the location of the text file as an argument. There are multiple reading methods to perform these operations.

  • read() – It reads the entire content of the file.

  • read(n) – It reads n characters of the text file.

  • readline() – It reads character line by line at a time. If we need to read the first two lines, the readline() method is to be used twice.

  • readlines() – it reads line by line and stores them in a list.

Example

Code Implementation with read()

#open the file for read operation
f = open('pythontext.txt')
#reads the entire file content and prints in console
print(f.read())
#close the file
f.close()

Code Implementation with read(n)

#open the file for read operation
f = open('pythontext.txt')
#reads 4 characters as passed as parameter and prints in console
print(f.read(4))
#close the file
f.close()

Code Implementation with readline()

#open the file for read operation
f = open('pythontext.txt')
# reads line by line
l = f.readline()
while l!= "":
print(l)
l = f.readline()
#close the file
f.close()

Code Implementation with readlines()

#open the file for read operation
f = open('pythontext.txt')
# reads line by line and stores them in list
for l in f.readlines():
print(l)
#close the file
f.close()

Updated on: 29-Jul-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements