如何使用python读取Selenium中的文本文件?
我们可以通过先创建一个txt文件并在其中包含内容,来使用python阅读Selenium中的文本文件。
首先,我们需要打开文件并提及文本文件位置的路径作为参数。有多种读取方法可以执行这些操作。
read()–读取文件的全部内容。
read(n) –读取文本文件的n个字符。
readline()–一次一行一行地读取字符。如果我们需要阅读前两行,则该readline()方法将使用两次。
readlines()–逐行读取并将它们存储在列表中。
示例
代码实现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()使用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()代码实现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()代码实现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()热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短