如何在 Python 中使用 Selenium 读取文本文件?
首先要创建一个文本文件并包含内容,我们才能使用 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()
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP