How to write a text file in Selenium with python?


We can write 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 in write mode and mention the path of the location of the text file as an argument. There are multiple reading methods to perform these operations.

  • write() – It writes the string in one line in a text file.

  • writelines() – It writes more than one string in a text file.

Example

Code Implementation with write().

#open the file for write operation
f = open('hello.txt' , 'w')
#writes the new content
f.write('Tutorialspoint')
#close the file
f.close()
# again open the file for read
f = open('hello.txt' , 'r')
#reads the file content and prints in console
print(f.read())
#close the file
f.close()

Code Implementation with writelines()

#open the file for write operation
f = open('hello.txt' , 'w')
lines = ["Tutorialspoint", "Selenium"]
#writes the new content
f.writelines(lines)
#close the file
f.close()
# again open the file for read
f = open('hello.txt' , 'r')
#reads the file content and prints in console
print(f.read())
#close the file
f.close()

Updated on: 29-Jul-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements