8

Is there a way to get the path and the file name of the current QGIS project from a Python script? I'm currently trying to develop a Python plugin for QGIS and I need to create a file with a similar name in the same folder.

20

You can use the following method from the QgsProject class to retrieve the path to the project file:

from qgis.core import *
prjpath = QgsProject.instance().fileName()

If there is no project loaded, or the current project has not yet been saved, this will return an empty QString:

PyQt4.QtCore.QString(u'')

You can convert the project file path further to a Python Unicode string (if needed) with:

unicode(prjpath)

However, if you intend to have your plugin be cross-platform, you are better off not working with the file path as a string in Python, but leverage Qt's excellent QFileInfo class:

from PyQt4.QtCore import *
from qgis.core import *

prjfi = QFileInfo(QgsProject.instance().fileName())
prjfi.absolutePath()  # what you are probably looking for

The QFileInfo class (along with QFile and QDir) will handle many cross-platform filesystem issues for you, and inclusively provide methods that would otherwise be spread across more Python classes.

1
  • 1
    you can also use QgsProject.instance().homePath() to get the path directly Jul 26 '19 at 9:37

Not the answer you're looking for? Browse other questions tagged or ask your own question.