Blue Square
Blue Square

Reputation: 31

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?

Upvotes: 1

Views: 908

Answers (2)

eyllanesc
eyllanesc

Reputation: 243993

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

Upvotes: 4

Milk
Milk

Reputation: 2655

From the 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);

Upvotes: 1

Related Questions