Getting path of project, or layer file in PyQGIS?

For python console:

QgsProject.instance().readPath("./") # also try "../"

Or with

dir(QgsProject.instance())

you find something like

fileName()

For python plugin (not tested!):

from PyQt4.QtGui import QMessageBox
from qgis.core import QgsProject
path_absolute = QgsProject.instance().readPath("./")
QMessageBox.information(None, "Title", "AP: " + unicode(path_absolute))

To access a vector file path, on a active layer, this code works well in Python Console:

>>>import os
>>>myfilepath= iface.activeLayer().dataProvider().dataSourceUri()
>>>myfilepath
u'/home/zeito/tiznados_canoa.tif'
>>>(myDirectory,nameFile) = os.path.split(myfilepath)
>>>myDirectory
u'/home/zeito'
>>>nameFile
u'tiznados_canoa.tif'

It was tested with my 'tiznados_canoa.tif' raster as a active layer.


If you want to access a vector file path, on a active layer, this seems to work:

myfilepath= os.path.dirname( unicode( qgis.utils.iface.activeLayer().dataProvider().dataSourceUri() ) ) ;
fic = myfilepath + "[% "FILE" %]"

then to open a picture or text located in same directory as mylayer:

from PyQt4 import QtWebKit, QtCore ; vue=QtWebKit.QWebView() vue.setUrl( QtCore.QUrl( fic ) ) ; vue.show()

Tags:

Pyqgis

Layers