Reading about Python? Actually practice it. Try PyChallenge free

Python Tutorial

QT4 File Dialog

In this short tutorial you will learn how to create a file dialog and load its file contents. The file dialog is needed in many applications that use file access.

Related course:
Practice Python with interactive exercises

File Dialog Example To get a filename (not file data) in PyQT you can use the line:

filename = QFileDialog.getOpenFileName(w, 'Open File', '/')

If you are on Microsoft Windows use

filename = QFileDialog.getOpenFileName(w, 'Open File', 'C:\')

An example below (includes loading file data):

#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *

# Create an PyQT4 application object. a = QApplication(sys.argv)

# The QWidget widget is the base class of all user interface objects in PyQt4. w = QWidget()

# Set window size. w.resize(320, 240)

# Set window title w.setWindowTitle("Hello World!")

# Get filename using QFileDialog filename = QFileDialog.getOpenFileName(w, 'Open File', '/') print(filename)

# print file contents with open(filename, 'r') as f: print(f.read())

# Show window w.show()

sys.exit(a.exec_())

Result (output may vary depending on your operating system):

pyqt_file_open PyQt File Open Dialog.

Download PyQT Code (Bulk Collection)

BackNext