The best way to get a filename from the user is to have them browse to the file using a dialog. You can have the user type in a filename using the text input dialog, but this method is prone to errors. In this recipe, we'll create a file dialog and print the chosen filename to the console.
Open the QGIS Python Console by selecting the Plugins menu and then clicking on Python Console.
In this recipe, we will create and configure the dialog, browse to a file, and print the chosen filename, as follows:
from PyQt4.QtGui import *
qfd = QFileDialog() title = 'Open File'
path = "/Users/joellawhead/qgis_data"
f = QFileDialog.getOpenFileName(qfd, title, path)
print f
The file dialog simply provides a filename. After the user selects the file, you must open it or perform some other operation on it. If the user cancels the file dialog, the file variable is just an empty string. You can use the QFileInfo
object to get the path of the selected file:
from PyQt4.QtCore import *path = QFileInfo(f).path()
Then, you can save this path in the project settings, as demonstrated in Chapter 1, Automating QGIS. This way, next time when you open a file dialog, you will start in the same directory location as the previous file, which is usually more convenient.