4

In QGIS, I've tried to remove a layer, execute a processing and overwrite the input layer. This in my Python code:

from qgis.core import *

for lyr in QgsProject.instance().mapLayers().values():
    if lyr.name() == "test":
        QgsProject.instance().removeMapLayers([lyr.id()])

infn =  QgsProject.instance().homePath()+"/temp.shp"
outfn = QgsProject.instance().homePath()+"/temp.shp"

processing.run("native:refactorfields", {'INPUT':infn,\
            'FIELDS_MAPPING':[{'expression': '\"Field1\"','length': 10,'name': 'Field1','precision': 0,'type': 10},\
            {'expression': '\"Field2\"','length': 50,'name': 'Field2','precision': 0,'type': 10}],\
            'OUTPUT':outfn})

The layer is successfully removed from the legend but I received this error for the output file:

error OGR: C:/temp/temp.shp is not a directory.

It would seem as if the layer remained in memory and did not allow to overwrite.

Any help?

1 Answer 1

3

I usually have this problem when input and output path are the same. The error caused by the temp.shp file already exists in the output directory while the processing algorithm is saving the result. You should use a different directory or file name.

According to the note in QGIS source code, it comes from OGR.

My guess is that while the output file is being saved to disk, the input file has not been unlocked yet. And OGR throws that error. If you check the folder, you see that .shp and .dbf files are still there. You probably cannot delete them for a while.

2
  • Thank for the answer. I was hoping there was a solution to unlock the file. I don't know the reason but if I remove the layer manually the overwrite it is possible.
    – ste
    Apr 30, 2021 at 20:19
  • @ste I couldn't find a solution, too. Therefore, I use the method I mentioned. Apr 30, 2021 at 20:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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