Pyside6 QFile


Pyside6的QFile类提供了一个读取和写入文件的接口,QFile可以操作文本文件和二进制文件。更多关于QFile类的说明可以参考下面的文档。

https://doc.qt.io/qtforpython-6/PySide6/QtCore/QFile.html#qfile

QFile使用

QFile常用函数

函数作用
open打开文件
readLine读取一行数据,遇到换行符(0x0A)结束
readAll读取全部数据
write写入数据
close关闭文件
exists判断文件是否存在
rename重命名文件
remove删除文件
copy复制文件

本章节例程基于test.bin和test.txt文件进行测试
在这里插入图片描述

文件编辑类函数

判断文件是否存在

exists函数用来判断一个文件是否存在,如果文件存在,则返回True,否则返回False。

if QFile('test.txt').exists() == True: # 判断test.txt文件是否存在
    print('test.txt 存在')
else :
    print('test.txt 不存在')

if QFile('test.bin').exists() == True: # 判断test.bin文件是否存在
    print('test.bin 存在')
else :
    print('test.bin 不存在')

if QFile('download.bin').exists() == True: # 判断download.bin文件是否存在
    print('download.bin 存在')
else :
    print('download.bin 不存在')

在这里插入图片描述

重命名文件

使用rename函数可以重命名文件,前提是文件必须存在。

file1 = QFile('test.txt')
if file1.exists() == True:
    file1.rename('rename_test.txt')
    print('test.txt 文件重命名成功')
else:
    print('test.txt 不存在 ,重命名失败')

file2 = QFile('download.bin')
if file2.exists() == True:
    file2.rename('rename_download.bin')
    print('download.bin 文件重命名成功')
else:
    print('download.bin 不存在 ,重命名失败')
  • 重命名前

在这里插入图片描述

  • 重命名后

在这里插入图片描述

删除文件函数

使用remove函数可以删除文件,前提是文件必须存在。

file1 = QFile('remove.txt')
if file1.exists() == True:
    file1.remove('remove.txt')
    print('remove.txt 文件删除成功')
else:
    print('remove.txt 文件 删除失败')

file2 = QFile('download.bin')
if file2.exists() == True:
    file2.remove('rename_download.bin')
    print('download.bin 文件删除成功')
else:
    print('download.bin 删除失败')
  • 新建remove.txt文件
    在这里插入图片描述
  • 删除remove.txt文件

在这里插入图片描述

复制文件

使用copy函数可以复制文件,前提是文件必须存在。

file1 = QFile('test.bin')
if file1.exists() == True:
    file1.copy('copy_test.bin')
    print('copy_test.bin 文件复制成功')
else:
    print('copy_test.bin 文件 复制失败')

file2 = QFile('download.bin')
if file2.exists() == True:
    file2.copy('copy_download.bin')
    print('copy_download.bin 文件复制成功')
else:
    print('copy_download.bin 文件 复制失败')

在这里插入图片描述
在这里插入图片描述

文件内容操作类函数

文件打开函数

使用open函数可以打开文件,开发者可以在打开函数的时候选择一些参数,这些参数将限制文件的一些具体操作。

NotOpen                  : QIODeviceBase.OpenModeFlag = ... # 0x0 
ReadOnly                 : QIODeviceBase.OpenModeFlag = ... # 0x1 
WriteOnly                : QIODeviceBase.OpenModeFlag = ... # 0x2 
ReadWrite                : QIODeviceBase.OpenModeFlag = ... # 0x3 
Append                   : QIODeviceBase.OpenModeFlag = ... # 0x4 
Truncate                 : QIODeviceBase.OpenModeFlag = ... # 0x8 
Text                     : QIODeviceBase.OpenModeFlag = ... # 0x10
Unbuffered               : QIODeviceBase.OpenModeFlag = ... # 0x20
NewOnly                  : QIODeviceBase.OpenModeFlag = ... # 0x40
ExistingOnly             : QIODeviceBase.OpenModeFlag = ... # 0x80

以上是open函数的一些具体操作,常用的是ReadOnly、WriteOnly、ReadWrite、Append和Truncate。

文件关闭函数

使用close函数可以打开文件,如果往一个文件写入内容后,需要调用close函数才会将新增加的内容写入到文件中,否则内容只会保留在内存中。

文件读取函数

文件读取有3个函数可以使用,分别是read、readLine、readall。这3个函数读到的数据都是bytes类型。

  • read:读取若干个字节的内容
  • readLine:读取一行内容,遇到换行符(0x0A)停止
  • readall:读取全部内容
read函数使用
  • 文本文件内容
    在这里插入图片描述
  • 二进制文件内容
    在这里插入图片描述
file1 = QFile('test.txt')                                                 
if file1.exists() == True:                                                
    file1.open(QFile.ReadOnly) # 只读方式打开文件                         
    print('test.txt 文件存在')                                            
    print("test.txt read %d bytes:",file1.size(),file1.read(file1.size()))
    file1.close() # 关闭文件
else:                                                                     
    print('test.bin 文件 不存在')                                         
                                                                          
file2 = QFile('test.bin')                                                 
if file2.exists() == True:                                                
    file2.open(QFile.ReadOnly) # 只读方式打开文件                         
    print('test.bin 文件存在')                                            
    print("test.bin read 16 bytes:",bytes(file2.read(16)).hex(' ', 1))  
    file2.close() # 关闭文件  
else:                                                                     
    print('test.bin 文件 不存在')                                         

在这里插入图片描述

readLine函数使用
  • 文本文件内容

在这里插入图片描述

  • 二进制文件内容
    在这里插入图片描述
file1 = QFile('test.txt')
if file1.exists() == True:
    file1.open(QFile.ReadOnly) # 只读方式打开文件
    print('test.txt 文件存在')
    print("test.txt read ",file1.readLine())
    file1.close() # 关闭文件
else:
    print('test.bin 文件 不存在')

file2 = QFile('test.bin')
if file2.exists() == True:
    file2.open(QFile.ReadOnly) # 只读方式打开文件
    print('test.bin 文件存在')
    print("test.bin read:",bytes(file2.readLine()).hex(' ', 1)) 
    file2.close() # 关闭文件
else:
    print('test.bin 文件 不存在')

在这里插入图片描述

readAll函数使用
  • 文本文件内容
    在这里插入图片描述
  • 二进制文件内容

在这里插入图片描述

file1 = QFile('test.txt')
if file1.exists() == True:
    file1.open(QFile.ReadOnly) # 只读方式打开文件
    print('test.txt 文件存在')
    print("test.txt read ",file1.readAll())
    file1.close() # 关闭文件
else:
    print('test.bin 文件 不存在')

file2 = QFile('test.bin')
if file2.exists() == True:
    file2.open(QFile.ReadOnly) # 只读方式打开文件
    print('test.bin 文件存在')
    print("test.bin read:",bytes(file2.readAll()).hex(' ', 1)) 
    file2.close() # 关闭文件
else:
    print('test.bin 文件 不存在')        

在这里插入图片描述

文件写入函数

使用write函数可以往文件中写入内容,写入的数据必须是bytes类型。在使用open函数打开文件时可以设置写文件的操作权限。

权限作用
WriteOnly只写操作,会覆盖原文件内容,如果文件不存在创建文件
Append追加写操作,会在原文件的内容最后添加新内容,如果文件不存在创建文件
Truncate以重写模式打开,写入的数据会将原有数据全部清除,通常跟WriteOnly搭配使用
追加方式写文件
  • 文本文件原内容
    在这里插入图片描述
  • 二进制文件原内容
    在这里插入图片描述
file1 = QFile('test.txt')
file1.open(QFile.Append) # 追加写方式打开文件
file1.write(b'ABCDEFGhjiklmn') # 追加写文件
file1.close() # 关闭文件

file2 = QFile('test.bin')
file2.open(QFile.Append) # 追加写方式打开文件
file2.write(b'ABCDEFGhjiklmn') # 追加写文件
file2.close() # 关闭文件

在这里插入图片描述
在这里插入图片描述

重写方式写文件
  • 文本文件原内容
    在这里插入图片描述
  • 二进制文件原内容

在这里插入图片描述

file1 = QFile('test.txt')
file1.open(QFile.WriteOnly | QFile.Truncate)  
file1.write(b'ABCDEFGhjiklmn')  
file1.close() # 关闭文件

file2 = QFile('test.bin')
file2.open(QFile.WriteOnly | QFile.Truncate) 
file2.write(b'ABCDEFGhjiklmn') 
file2.close() # 关闭文件

在这里插入图片描述
在这里插入图片描述

程序

界面程序

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>243</width>
    <height>264</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <layout class="QVBoxLayout" name="verticalLayout">
    <item>
     <widget class="QTabWidget" name="tabWidget">
      <property name="currentIndex">
       <number>0</number>
      </property>
      <widget class="QWidget" name="tab">
       <attribute name="title">
        <string>文件编辑</string>
       </attribute>
       <layout class="QVBoxLayout" name="verticalLayout_3">
        <item>
         <layout class="QVBoxLayout" name="verticalLayout_2">
          <item>
           <widget class="QPushButton" name="pushButton">
            <property name="text">
             <string>判断文件是否存在</string>
            </property>
           </widget>
          </item>
          <item>
           <widget class="QPushButton" name="pushButton_2">
            <property name="text">
             <string>重命名文件</string>
            </property>
           </widget>
          </item>
          <item>
           <widget class="QPushButton" name="pushButton_3">
            <property name="text">
             <string>删除文件</string>
            </property>
           </widget>
          </item>
          <item>
           <widget class="QPushButton" name="pushButton_4">
            <property name="text">
             <string>复制文件</string>
            </property>
           </widget>
          </item>
         </layout>
        </item>
       </layout>
      </widget>
      <widget class="QWidget" name="tab_2">
       <attribute name="title">
        <string>读文件</string>
       </attribute>
       <layout class="QVBoxLayout" name="verticalLayout_5">
        <item>
         <layout class="QVBoxLayout" name="verticalLayout_4">
          <item>
           <widget class="QPushButton" name="pushButton_5">
            <property name="text">
             <string>读取若干个文件内容</string>
            </property>
           </widget>
          </item>
          <item>
           <widget class="QPushButton" name="pushButton_6">
            <property name="text">
             <string>读取一行文件内容</string>
            </property>
           </widget>
          </item>
          <item>
           <widget class="QPushButton" name="pushButton_7">
            <property name="text">
             <string>读取全部文件内容</string>
            </property>
           </widget>
          </item>
         </layout>
        </item>
       </layout>
      </widget>
      <widget class="QWidget" name="tab_3">
       <attribute name="title">
        <string>写文件</string>
       </attribute>
       <layout class="QVBoxLayout" name="verticalLayout_7">
        <item>
         <layout class="QVBoxLayout" name="verticalLayout_6">
          <item>
           <widget class="QPushButton" name="pushButton_8">
            <property name="text">
             <string>追加方式写文件</string>
            </property>
           </widget>
          </item>
          <item>
           <widget class="QPushButton" name="pushButton_9">
            <property name="text">
             <string>重写方式写文件</string>
            </property>
           </widget>
          </item>
         </layout>
        </item>
       </layout>
      </widget>
     </widget>
    </item>
   </layout>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>243</width>
     <height>22</height>
    </rect>
   </property>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>

主程序

# Import Qt libraries
from PySide6.QtWidgets import *
from PySide6.QtCore import QFile,QByteArray
# Import UI developed in Qt Creator
from qfile_ui import Ui_MainWindow  # 导入界面
# Import PseudoSensor
# Import system tools and datetime
import sys
import statistics
import time
from datetime import datetime

# Create and start the Qt application
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        # 设置界面为用户设计的界面
        self.ui = Ui_MainWindow() 
        self.ui.setupUi(self) 

        self.ui.pushButton.clicked.connect(self.file_exists)
        self.ui.pushButton_2.clicked.connect(self.file_rename)
        self.ui.pushButton_3.clicked.connect(self.file_remove)
        self.ui.pushButton_4.clicked.connect(self.file_copy)
        self.ui.pushButton_5.clicked.connect(self.file_read)
        self.ui.pushButton_6.clicked.connect(self.file_readline)
        self.ui.pushButton_7.clicked.connect(self.file_readall)
        self.ui.pushButton_8.clicked.connect(self.file_writeappend)
        self.ui.pushButton_9.clicked.connect(self.file_rewrite)
        
    def file_exists(self):
        if QFile('test.txt').exists() == True: # 判断test.txt文件是否存在
            print('test.txt 存在')
        else :
            print('test.txt 不存在')
       
        if QFile('test.bin').exists() == True: # 判断test.bin文件是否存在
            print('test.bin 存在')
        else :
            print('test.bin 不存在')

        if QFile('download.bin').exists() == True: # 判断download.bin文件是否存在
            print('download.bin 存在')
        else :
            print('download.bin 不存在')
    
    def file_rename(self):
        file1 = QFile('test.txt')
        if file1.exists() == True:
            file1.rename('rename_test.txt')
            print('test.txt 文件重命名成功')
        else:
            print('test.txt 不存在 ,重命名失败')

        file2 = QFile('download.bin')
        if file2.exists() == True:
            file2.rename('rename_download.bin')
            print('download.bin 文件重命名成功')
        else:
            print('download.bin 不存在 ,重命名失败')

    def file_remove(self):
        file1 = QFile('remove.txt')
        if file1.exists() == True:
            file1.remove('remove.txt')
            print('remove.txt 文件删除成功')
        else:
            print('remove.txt 文件 删除失败')

        file2 = QFile('download.bin')
        if file2.exists() == True:
            file2.remove('rename_download.bin')
            print('download.bin 文件删除成功')
        else:
            print('download.bin 删除失败')

    def file_copy(self):
        file1 = QFile('test.bin')
        if file1.exists() == True:
            file1.copy('copy_test.bin')
            print('copy_test.bin 文件复制成功')
        else:
            print('copy_test.bin 文件 复制失败')

        file2 = QFile('download.bin')
        if file2.exists() == True:
            file2.copy('copy_download.bin')
            print('copy_download.bin 文件复制成功')
        else:
            print('copy_download.bin 文件 复制失败')

    def file_read(self):
        file1 = QFile('test.txt')
        if file1.exists() == True:
            file1.open(QFile.ReadOnly) # 只读方式打开文件
            print('test.txt 文件存在')
            print("test.txt read %d bytes:",file1.size(),file1.read(file1.size()))
            file1.close() # 关闭文件
        else:
            print('test.bin 文件 不存在')

        file2 = QFile('test.bin')
        if file2.exists() == True:
            file2.open(QFile.ReadOnly) # 只读方式打开文件
            print('test.bin 文件存在')
            print("test.bin read 16 bytes:",bytes(file2.read(16)).hex(' ', 1)) # 读取16个字节
            file2.close() # 关闭文件
        else:
            print('test.bin 文件 不存在')

    def file_readline(self):
        file1 = QFile('test.txt')
        if file1.exists() == True:
            file1.open(QFile.ReadOnly) # 只读方式打开文件
            print('test.txt 文件存在')
            print("test.txt read ",file1.readLine())
            file1.close() # 关闭文件
        else:
            print('test.bin 文件 不存在')

        file2 = QFile('test.bin')
        if file2.exists() == True:
            file2.open(QFile.ReadOnly) # 只读方式打开文件
            print('test.bin 文件存在')
            print("test.bin read:",bytes(file2.readLine()).hex(' ', 1)) 
            file2.close() # 关闭文件
        else:
            print('test.bin 文件 不存在')

    def file_readall(self):
        file1 = QFile('test.txt')
        if file1.exists() == True:
            file1.open(QFile.ReadOnly) # 只读方式打开文件
            print('test.txt 文件存在')
            print("test.txt read ",file1.readAll())
            file1.close() # 关闭文件
        else:
            print('test.bin 文件 不存在')

        file2 = QFile('test.bin')
        if file2.exists() == True:
            file2.open(QFile.ReadOnly) # 只读方式打开文件
            print('test.bin 文件存在')
            print("test.bin read:",bytes(file2.readAll()).hex(' ', 1)) 
            file2.close() # 关闭文件
        else:
            print('test.bin 文件 不存在')

    def file_writeappend(self):
        file1 = QFile('test.txt')
        file1.open(QFile.Append) # 追加写方式打开文件
        file1.write(b'ABCDEFGhjiklmn') # 追加写文件
        file1.close() # 关闭文件

        file2 = QFile('test.bin')
        file2.open(QFile.Append) # 追加写方式打开文件
        file2.write(b'ABCDEFGhjiklmn') # 追加写文件
        file2.close() # 关闭文件


    def file_rewrite(self):
        file1 = QFile('test.txt')
        file1.open(QFile.WriteOnly | QFile.Truncate)  
        file1.write(b'ABCDEFGhjiklmn')  
        file1.close() # 关闭文件

        file2 = QFile('test.bin')
        file2.open(QFile.WriteOnly | QFile.Truncate) 
        file2.write(b'ABCDEFGhjiklmn') 
        file2.close() # 关闭文件

    def closeAndExit(self):
        sys.exit()

if __name__ == "__main__":
    app = QApplication(sys.argv) # 初始化QApplication

    # 初始化界面并显示界面
    window = MainWindow() 
    window.show() 
    window.setFixedSize(window.width(), window.height())
    sys.exit(app.exec())
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值