Python PyQt5 读取文本文件内容 - 行读取示例
你可以使用QtCore模块中的QFile和QTextStream来打开和读取文本文件。
首先,导入QtCore模块:
from PyQt5.QtCore import QFile, QTextStream
然后,使用QFile打开文本文件:
file = QFile('your_file_path.txt')
if not file.open(QFile.ReadOnly | QFile.Text):
print('无法打开文件')
return
接下来,创建一个QTextStream对象来读取文件内容:
stream = QTextStream(file)
while not stream.atEnd():
line = stream.readLine()
print(line)
最后,记得在读取完成后关闭文件:
file.close()
完整的示例代码如下:
from PyQt5.QtCore import QFile, QTextStream
file = QFile('your_file_path.txt')
if not file.open(QFile.ReadOnly | QFile.Text):
print('无法打开文件')
return
stream = QTextStream(file)
while not stream.atEnd():
line = stream.readLine()
print(line)
file.close()
记得将'your_file_path.txt'替换为你要打开的文本文件的路径。
原文地址: http://www.cveoy.top/t/topic/pkzw 著作权归作者所有。请勿转载和采集!