PyQt5读取csv文件并显示内容


前序

查询了很多资料,看了很多博客,我就是简单的想用pyqt5读取csv文件并显示内容,这一简单的想法就是不能实现。自己偶然的一次尝试中,解决了这个问题。按照直接读取txt文件的方式去去读csv。

正文

在这里插入图片描述
上面是作者的qt界面,我们点击QFile,就能打开文件,将内容显示

在这里插入图片描述
我们在on_actQFile_Open_triggered这个函数完成槽与信号的相关操作,本来是

文本文件(.*txt)改成CSV文件(*.csv)

代码实现

# 首先要用Qt creator 设计自己的界面,然后用PyQt5和Qt进行关联
# 不是全部的代码,是关键代码,主要看on_actQFile_Open_triggered这个函数
##  ==============自定义功能函数========================
   def __openByIODevice(self,fileName):  ##用QFile打开文件
      fileDevice=QFile(fileName)
      if not fileDevice.exists():  #判断文件是否存在
         return False

      if not fileDevice.open(QIODevice.ReadOnly | QIODevice.Text):
         return False

###整个文件一次性读取的方式,可行
##      qtBytes=fileDevice.readAll() #返回QByteArray类型
##      pyBytes=bytes(qtBytes.data())  # 将QByteArray转换为bytes类型
##      text=pyBytes.decode("utf-8")  #用utf-8编码为字符串
##      self.ui.textEdit.setPlainText(text)
      
##  逐行读取方式,可行
      try:
         self.ui.textEdit.clear()
         while not fileDevice.atEnd():
            qtBytes = fileDevice.readLine()  # 返回QByteArray类型
            pyBytes=bytes(qtBytes.data())    # QByteArray转换为bytes类型
            lineStr=pyBytes.decode("utf-8")  #bytes转换为str型
            lineStr=lineStr.strip()          #去除结尾增加的空行
            self.ui.textEdit.appendPlainText(lineStr)
      finally:
         fileDevice.close()
         
      return True


##  ==========由connectSlotsByName()自动连接的槽函数============
   
   @pyqtSlot()   ##用QFile 打开文件
   def on_actQFile_Open_triggered(self):
      curPath=QDir.currentPath()    #获取系统当前目录
      title="打开一个文件"    #对话框标题
      filt="程序文件(*.h *.cpp *.py);;CSV文件(*.csv);;所有文件(*.*)"   #文件过滤器
      fileName,flt=QFileDialog.getOpenFileName(self,title,curPath,filt)
      if (fileName == ""):
         return

      if self.__openByIODevice(fileName):
         self.ui.statusBar.showMessage(fileName)
      else:
         QMessageBox.critical(self,"错误","打开文件失败")

   @pyqtSlot()   ##用QFile 另存文件
   def on_actQFile_Save_triggered(self):
      curPath=QDir.currentPath()    #获取系统当前目录
      title="另存为一个文件"        #对话框标题
      filt="Python程序(*.py);; C++程序(*.h *.cpp);;csv文件(*.csv);;所有文件(*.*)"  #文件过滤器
      fileName,flt=QFileDialog.getSaveFileName(self,title,curPath,filt)
      if (fileName==""):
         return

      if self.__saveByIODevice(fileName):
         self.ui.statusBar.showMessage(fileName)
      else:
         QMessageBox.critical(self,"错误","保存文件失败")

结果显示

在这里插入图片描述

代码下载

完整代码下载链接:链接:https://pan.baidu.com/s/1jmxBsScd75VGGpopppupjg ,提取码:i16t

  • 7
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
可以通过Python自带的csv模块读取csv文件,然后使用PyQt5的QTableView控件来显示csv文件中的数据。以下是一个读取csv文件并将其显示在QTableView中的示例代码: ```python import csv from PyQt5.QtWidgets import QApplication, QTableView from PyQt5.QtCore import Qt, QAbstractTableModel class CsvModel(QAbstractTableModel): def __init__(self, data): QAbstractTableModel.__init__(self) self._data = data def rowCount(self, parent=None): return len(self._data) def columnCount(self, parent=None): if len(self._data) > 0: return len(self._data[0]) return 0 def data(self, index, role): if not index.isValid(): return None if role == Qt.DisplayRole: return self._data[index.row()][index.column()] def headerData(self, section, orientation, role): if role != Qt.DisplayRole: return None if orientation == Qt.Horizontal: return "Column %d" % section else: return "Row %d" % section class CsvViewer(QTableView): def __init__(self, data): QTableView.__init__(self) self.model = CsvModel(data) self.setModel(self.model) if __name__ == '__main__': with open('data.csv', 'r') as file: reader = csv.reader(file) data = list(reader) app = QApplication([]) view = CsvViewer(data) view.show() app.exec_() ``` 在上面的代码中,我们首先通过Python自带的csv模块读取csv文件,然后将其转化为一个二维列表。接着,我们定义了一个CsvModel类,该类继承自QAbstractTableModel,用于将读取csv数据转化为一个可以在QTableView中显示的模型。最后,我们定义了一个CsvViewer类,该类继承自QTableView,用于显示CsvModel中的数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水花

您的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值