python logo

open file python


Python hosting: Host, run, and code Python in the cloud!

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:

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





Leave a Reply:




Paul b Sat, 23 Jan 2016

Thanks for these great tutorials Frank. They are very helpful!

Paul b Sat, 23 Jan 2016

For windows the line should read:

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

You can also just do the following to start in current working directory:

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

Nanodano Fri, 29 Jan 2016

It's best to choose an option that is cross platform. Another option is to open the file dialog to the users home directory. Here is a cross platform way of doing that with the Python standard library:

from os.path import expanduser
home_dir = expanduser('~')

Melissa Sat, 26 Mar 2016

Hi there,
I'm somewhat at a loss on labels...how do these work in PYQT4
Thanks
Melissa

Frank Mon, 28 Mar 2016

To add a label to a window you can call QLabel. I made an example:


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()
# Add label
nameLabel = QLabel("A label in PyQT", w)
nameLabel.move(100, 80)
# Set window size.
w.resize(320, 240)
# Set window title
w.setWindowTitle("PyQT Label Example pythonspot.com")
# Show window
w.show()
sys.exit(a.exec_())

Kevin Sun, 12 Jun 2016

How about load an image file and display it?