1

I wish to change the directory of a file up of one level in the QGIS Macros. I tried this code but I got the Error:

File "", line 10, in openProject
TypeError: cdUp(self): first argument of unbound method must have type 'QDir'

my script :

from PyQt5 import *
from PyQt5.QtCore import QDir
def openProject():
 from qgis.core import QgsProject
 old_root_folder = "/home/qgis/base/1_QGISData"
 proj_root = QgsProject.instance().homePath()
 proj_files_folder = "/1_QGIS_Projetdata/"
 new_root_folder = QDir.cdUp(proj_root) + proj_files_folder
 print(new_root_folder)
 for layer in QgsProject.instance().mapLayers().values():
 name = layer.name()
 old_url = layer.dataProvider().dataSourceUri()
 new_url = old_url.replace(old_root_folder, new_root_folder)
 provider = layer.providerType()
 options = layer.dataProvider().ProviderOptions()
 layer.setDataSource(new_url, name, provider, options)
def saveProject():
 pass
def closeProject():
 pass

What do I do wrong?

PS: The proj_files_folder is in a totally different directory

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Aug 25, 2022 at 9:57

1 Answer 1

0

One issue is that QDir.cdUp(proj_root) will only return a bool not a string or path. If you import os and use the split and join functions it may be easier. Using os.path.dirname(your_path_here) will get the parent directory. An example below.

import os
from PyQt5 import *
from PyQt5.QtCore import QDir
def openProject():
 proj_root = QgsProject.instance().homePath()
 cur_path = QDir.currentPath()
 print(cur_path)
 print(proj_root)
 proj_files_folder = "/1_QGIS_Projetdata/"
 bool_change = QDir.cdUp(QDir(cur_path))
 print(bool_change)
 print(QDir.currentPath())
 
 parent = os.path.dirname(cur_path)
 print(parent)
 data_dir = os.path.join(parent, proj_files_folder)
 print(data_dir)
openProject()
answered Aug 25, 2022 at 12:47

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.