PyQt的QTextStream类对文本的读写简要说明

时间:2021-07-26 22:59:01

本文是关于python的QTextStream类读写文本简要说明。
QTextStream与QDataStream不同的时,前者是处理文本,后者二进制文件。因而QTextStream特别注意文本格式编码的问题,读取编码和写出编码方式如果存在不同,则会造成相关数据的误读。
以下例子为创建一个类型结构Movie,然后将此类型通过QTextStream类保存到指定的文本文件,然后从文本文件将保存的内容读出,读写过程类似于Python标准库对普通的文件操作,但是此方式更加快捷,在开发PyQt Gui程序中,需要保存为文本格式,这个方法可以借用,但是注意不是所有的pyqt类型直接不经处理写入文本,毕竟还是要遵循文本的处理规则。文本文件的编码为UTF-8,文本的内容格式如下:
{{MOVIE}} God save world
1989 45 2017-01-14
{NOTES}
HELLO WORLD
{{ENDMOVIE}}

from PyQt5.QtCore import  QFile, QFileInfo, QIODevice,QTextStream
import datetime
CODEC = "UTF-8"
class Movie(object):
UNKNOWNYEAR = 1890
UNKNOWNMINUTES = 0
def __init__(self, title=None, year=UNKNOWNYEAR,
minutes=UNKNOWNMINUTES, acquired=None, notes=None)
:

self.title = title
self.year = year
self.minutes = minutes
self.acquired = (acquired if acquired is not None
else datetime.date.today())
self.notes = notes
class MovieContainer(object):

def __init__(self,fname,movies):
self.__fname = fname
self.__movies = movies

def saveQTextStream(self):
error = None
fh = None
try:
fh = QFile(self.__fname)
if not fh.open(QIODevice.WriteOnly):
raise IOError(str(fh.errorString()))
stream = QTextStream(fh)
stream.setCodec(CODEC)
stream << "{{MOVIE}} " << movie.title << "\n" \
<< movie.year << " " << movie.minutes << " " \
<< str(movie.acquired) \
<< "\n{NOTES}"
if movie.notes:
stream << "\n" << movie.notes
stream << "\n{{ENDMOVIE}}\n"
except EnvironmentError as e:
error = "Failed to save: {0}".format(e)
finally:
if fh is not None:
fh.close()
if error is not None:
print(error)
print("Saved 1 movie records to {0}".format(
QFileInfo(self.__fname).fileName()))


def loadQTextStream(self):
error = None
fh = None
try:
fh = QFile(self.__fname)
if not fh.open(QIODevice.ReadOnly):
raise IOError(str(fh.errorString()))
stream = QTextStream(fh)
stream.setCodec(CODEC)
lino = 0
while not stream.atEnd():
title = year = minutes = acquired = notes = None
line = stream.readLine()
lino += 1
if not line.startswith("{{MOVIE}}"):
raise ValueError("no movie record found")
else:
title = line[len("{{MOVIE}}"):].strip()
print(title)
if stream.atEnd():
raise ValueError("premature end of file")
line = stream.readLine()
lino += 1
parts = line.split(" ")
if len(parts)!= 3:
raise ValueError("invalid numeric data")
year = int(parts[0])
minutes = int(parts[1])
print(year)
print(minutes)
ymd = parts[2].split("-")
if len(ymd) != 3:
raise ValueError("invalid acquired date")
acquired = datetime.date(int(ymd[0]),
int(ymd[1]), int(ymd[2]))
print(acquired)
if stream.atEnd():
raise ValueError("premature end of file")
line = stream.readLine()
lino += 1
if line != "{NOTES}":
raise ValueError("notes expected")
notes = ""
while not stream.atEnd():
line = stream.readLine()
lino += 1
if line == "{{ENDMOVIE}}":
if (title is None or year is None or
minutes is None or acquired is None or
notes is None):
raise ValueError("incomplete record")
break
else:
notes += line + "\n"
print(notes)
else:
raise ValueError("missing endmovie marker")
except (IOError, OSError, ValueError) as e:
error = "Failed to load: {0} on line {1}".format(e, lino)
finally:
if fh is not None:
fh.close()
if error is not None:
print(error)
print("Loaded 1 movie records from {0}".format(
QFileInfo(self.__fname).fileName()))

if __name__ == "__main__":

textdata=[["God save world",1989,45,None,"HELLO WORLD"]]
fname="/home/yrd/work/movie.datatxt"
for data in textdata:
movie=Movie(data[0],data[1],data[2],data[3],data[4])
moviecontainer=MovieContainer(fname, movie)
moviecontainer.saveQTextStream()
moviecontainer.loadQTextStream()

运行结果:
Saved 1 movie records to movie.datetxt
God save world
1989
45
2017-01-14
HELLO WORLD

Loaded 1 movie records from movie.datetxt