27

I am generating new raster files from vector layers on a project. I would like to save them in the same directory as the project or layer files.

How do I find this path using PyQGIS?

Taras
  • 32,823
  • 4
  • 66
  • 137
fccoelho
  • 1,237
  • 5
  • 13
  • 22

5 Answers5

27

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))

Taras
  • 32,823
  • 4
  • 66
  • 137
qräbnö
  • 494
  • 4
  • 9
21

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.

xunilk
  • 29,891
  • 4
  • 41
  • 80
  • 6
    Be aware in case of vector layer the path after file name contains also pipe and layer id (C:/shapes/test.shp|layerid=0). I use path = path [:path.rfind('|')] to remove it. – Miro Nov 09 '16 at 05:24
13

In QGIS 3.2 and above:

Project path:

QgsProject.instance().fileName() 
# OR
QgsProject.instance().absoluteFilePath() # C:/test/sample_project.qgz 

Project folder path:

QgsProject.instance().homePath()
# OR
QgsProject.instance().absolutePath()   # C:/test

In QGIS 2.x, 3.0 and 3.1:

Project path:

QgsProject.instance().fileName()  # C:/test/sample_project.qgs

Project folder path:

QgsProject.instance().homePath() # C:/test
Taras
  • 32,823
  • 4
  • 66
  • 137
Kadir Şahbaz
  • 76,800
  • 56
  • 247
  • 389
8

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()
rha
  • 394
  • 1
  • 4
  • Useful answer but what about the file name? You use "[% "FILE" %]" but I don't understand what does it means... – G M Aug 19 '13 at 20:59
6

I did test this on QGIS 3.4:

QgsProject.instance().fileName()

will return the entire path to the file

'C:/MyDirectory/18809_US66.qgz'
Taras
  • 32,823
  • 4
  • 66
  • 137
Cary H
  • 964
  • 9
  • 21