python文件获取并读取固定长度数据实例解析

一 概念

1 file 操作:

文件操作一般有open,write,read,close几种,这里重点是read固定长度数据。

read() 用于从文件读取指定的字节数,如果未给定或为负则读取所有。

本文中心不在概念,直接上源码。

二 源码解析

import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QFileDialog

class MyWindow(QtWidgets.QWidget):
    def __init__(self):
            super(MyWindow,self).__init__()
            self.myButton = QtWidgets.QPushButton(self)
            self.myButton.setObjectName("myButton")
            self.myButton.setText("Test")
            self.myButton.clicked.connect(self.msg)
    def msg(self):
            fileName1, filetype = QFileDialog.getOpenFileName(self,
                  "选取文件",
                  "./",
                  "All Files (*);;Text Files (*.txt)")  #设置文件扩展名过滤,注意用双分号间隔
            print(fileName1)
            file = open(fileName1,"r",encoding="utf-8")
            while True:
                data = file.read(20)
                if len(data) > 0:
                    print(len(data))
                    print(data)
                else:
                    print("read over")
                    break


if __name__=="__main__":
        app=QtWidgets.QApplication(sys.argv)
        myshow=MyWindow()
        myshow.show()
        sys.exit(app.exec_())

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章