Search code examples
pythonpyqtsizepyqt5filesize

Python: How can I obtain the filesize of a selected file in PyQt5?


In PyQt5, it is possible to select a file using QFileDialog. I understand how to obtain the file name, but how might one obtain the filesize?


Solution

  • Without opening the file:

    You must use the QFileInfo class and the size() method:

    filename, _ = QFileDialog.getOpenFileName(None, 'Open file')
    if filename != "":
        info = QFileInfo(filename)
        size = info.size()
        print(info)
    

    Opening the file:

    filename, _ = QFileDialog.getOpenFileName(None, 'Open file')
    if filename != "":
        file = QFile(filename)
        if file.open(QFile.ReadOnly):
            print(file.size())