如何在 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