Python: 如何获取PyQt5中选中文件的文件大小?

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

在 PyQt5 中,可以使用 QFileDialog select 文件。我知道如何获取文件名,但如何获取文件大小?

来自documentation

The file dialog has two view modes ... Detail also displays a list of file and directory names, but provides additional information alongside each name, such as the file size and modification date. Set the mode with setViewMode():

dialog.setViewMode(QFileDialog::Detail);

不打开文件:

您必须使用QFileInfo class and the size()方法:

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

打开文件:

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