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
1 Answer 1
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()