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_())

 

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