PyQt文本文件读写

  1 ##  ==============自定义功能函数========================
  2    def __openByIODevice(self,fileName):   ##用QFile打开文件
  3       fileDevice=QFile(fileName)
  4       # print("**",fileDevice.exists())
  5       # print("@@",fileDevice.open(QIODevice.ReadOnly | QIODevice.Text))
  6       if not fileDevice.exists():   #判断文件是否存在
  7          return False
  8       if not fileDevice.open(QIODevice.ReadOnly | QIODevice.Text):
  9          return False
 10       try:
 11          self.ui.textEdit.clear()
 12          while not fileDevice.atEnd():
 13             qtBytes = fileDevice.readLine()  #返回QByteArray类型
 14             pyBytes = bytes(qtBytes.data())  #将QByteArray转换为bytes类型
 15             lineStr = pyBytes.decode("utf-8")   #bytes转换为str类型
 16             lineStr = lineStr.strip()           #去除结尾增加的空行
 17             self.ui.textEdit.appendPlainText(lineStr)
 18       finally:
 19          fileDevice.close()
 20       return True
 21       pass
 22 
 23 
 24    def __saveByIODevice(self,fileName):   ##用QFile保存文件
 25       fileDevice=QFile(fileName)
 26       if not fileDevice.open(QIODevice.WriteOnly | QIODevice.Text):
 27          return False
 28       try:
 29          text=self.ui.textEdit.toPlainText()
 30          strBytes=text.encode("utf-8")
 31          fileDevice.write(strBytes)
 32       finally:
 33          fileDevice.close()
 34       return True
 35       pass
 36 
 37 
 38    def __openByStream(self,fileName):     ##用QTextStream打开文件
 39       fileDevice=QFile(fileName)
 40       if not fileDevice.exists():   #判断文件是否存在
 41          return False
 42       if not fileDevice.open(QIODevice.ReadOnly | QIODevice.Text):
 43          return False
 44       try:
 45          fileStream=QTextStream(fileDevice)
 46          fileStream.setAutoDetectUnicode(True)     #自动检测Unicode
 47          fileStream.setCodec("utf-8")
 48          self.ui.textEdit.clear()
 49          while not fileStream.atEnd():
 50             lineStr=fileStream.readLine()          #读取文件的一行读取出来的就是str
 51             self.ui.textEdit.appendPlainText(lineStr)    #添加到文本框显示
 52       finally:
 53          fileDevice.close()
 54       return True
 55       pass
 56 
 57 
 58    def __saveByStream(self,fileName):     ##用 QTextStream 保存文件
 59       fileDevice=QFile(fileName)
 60       if not fileDevice.open(QIODevice.WriteOnly | QIODevice.Text):
 61          return False
 62       try:
 63          fileStream=QTextStream(fileDevice)
 64          fileStream.setAutoDetectUnicode(True)     #自动检测Unicode
 65          fileStream.setCodec("utf-8")
 66          text=self.ui.textEdit.toPlainText()
 67          fileStream<<text
 68          fileStream<<"\n************在尾部添加的第一行"
 69       finally:
 70          fileDevice.close()
 71       return True
 72       pass
 73       
 74 
 75 ##  ==============event处理函数==========================
 76         
 77         
 78 ##  ==========由connectSlotsByName()自动连接的槽函数============
 79    
 80    @pyqtSlot()   ##用QFile 打开文件
 81    def on_actQFile_Open_triggered(self):
 82       curPath=QDir.currentPath()
 83       title="打开一个文件"
 84       filt="程序文件(*.h*.cpp*.py);;文本文件(*.txt);;所有文件(*.*)"
 85       fileName,flt=QFileDialog.getOpenFileName(self,title,curPath,filt)
 86       if fileName == "":
 87          return
 88       if self.__openByIODevice(fileName):
 89          self.ui.statusBar.showMessage(fileName)
 90       else:
 91          QMessageBox.critical(self,"错误","打开文件失败")
 92       pass
 93 
 94 
 95    @pyqtSlot()   ##用QFile 另存文件
 96    def on_actQFile_Save_triggered(self):
 97       curPath=QDir.currentPath()
 98       title="另存为一个文件"
 99       filt="Python程序(*.py);;C++程序(*.h*.cpp);;所有文件(*.*)"
100       fileName,flt=QFileDialog.getSaveFileName(self,title,curPath,filt)
101       if fileName == "":
102          return
103       if self.__saveByIODevice(fileName):
104          self.ui.statusBar.showMessage(fileName)
105       else:
106          QMessageBox.critical(self,"错误","保存文件失败")
107       pass
108 
109 
110    @pyqtSlot()   ##用QTextStream 打开文件
111    def on_actStream_Open_triggered(self):
112       curPath=QDir.currentPath()
113       title="打开一个文件"
114       filt="程序文件(*.h*.cpp*.py);;文本文件(*.txt);;所有文件(*.*)"
115       fileName,flt=QFileDialog.getOpenFileName(self,title,curPath,filt)
116       if fileName == "":
117          return
118       if self.__openByStream(fileName):
119          self.ui.statusBar.showMessage(fileName)
120       else:
121          QMessageBox.critical(self,"错误","打开文件失败")
122       pass
123 
124 
125    @pyqtSlot()   ##用QTextStream 另存文件
126    def on_actStream_Save_triggered(self):
127       curPath=QDir.currentPath()
128       title="另存为一个文件"
129       filt="Python程序(*.py);;C++程序(*.h*.cpp);;所有文件(*.*)"
130       fileName,flt=QFileDialog.getSaveFileName(self,title,curPath,filt)
131       if fileName == "":
132          return
133       if self.__saveByStream(fileName):
134          self.ui.statusBar.showMessage(fileName)
135       else:
136          QMessageBox.critical(self,"错误","保存文件失败")
137       pass
138 
139 
140    @pyqtSlot()   ##用 python 的file()打开文件
141    def on_actPY_Open_triggered(self):
142       curPath=QDir.currentPath()
143       title="打开一个文件"
144       filt="程序文件(*.h*.cpp*.py);;文本文件(*.txt);;所有文件(*.*)"
145       fileName,flt=QFileDialog.getOpenFileName(self,title,curPath,filt)
146       if fileName == "":
147          return
148       self.ui.textEdit.clear()
149       fileDevice=open(fileName,mode='r',encoding='utf-8')
150       try:
151          for eachLine in fileDevice:      #每次读取一行
152             lineStr = eachLine.strip()
153             self.ui.textEdit.appendPlainText(lineStr)
154          self.ui.statusBar.showMessage(fileName)
155       finally:
156          fileDevice.close()
157       pass
158 
159          
160    @pyqtSlot()   ##用 python的file() 保存文件
161    def on_actPY_Save_triggered(self):
162       curPath=QDir.currentPath()
163       title="另存为一个文件"
164       filt="Python程序(*.py);;C++程序(*.h*.cpp);;所有文件(*.*)"
165       fileName,flt=QFileDialog.getSaveFileName(self,title,curPath,filt)
166       if fileName == "":
167          return
168       text=self.ui.textEdit.toPlainText() #str类型
169       fileDevice=open(fileName,mode='w',encoding='utf-8')
170       try:
171          fileDevice.write(text)
172          self.ui.statusBar.showMessage(fileName)
173       finally:
174          fileDevice.close()
175       pass

 

上一篇:算法题:1~5随机数函数转化成1~7的随机函数(等概率)


下一篇:Vue.js 学习笔记(三)过滤器、实例及选项