本文是關於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