如何使用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 生日广州男生祝福语简短