如何使用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()热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿