6

How to replace name or delete .shp file from directory using Python QGIS ?

import os
import processing
input = "//input.shp"
output = "//output_100.shp"
interval = 100
processing.runalg("qgis:densifygeometriesgivenaninterval", input,    interval, output)
paths = (os.path.join(root, filename)
    for root, _, filenames in os.walk("C:/" + os.getenv('USERNAME') + "/SHP_Path")
    for filename in filenames)

for path in paths:
newname = path.replace('_100', '')
if newname != path:
    os.rename(path, newname)

Result:

WindowsError: [Error 183] Can't create existing file.

I think that I should delete input.shp before renaming output.shp to input.shp. But If I'll try to delete that files (.shp, .dbf, .shx) with code:

    filename="C:/" + os.getenv('USERNAME') + "/SHP_Path" + "//input.shp"
if os.path.exists(filename):
os.remove(filename)

I 've got result:

WindowsError: [Error 32] The process can not obtain access to the file because it is being used by another process :

1 Answer 1

5

I think there are 2 methods which could get around the issue:


  • Use memory layer as input

Create a copy of your input layer as a memory layer, this way you can continue to use the same data as your original input but it also 'frees' the shapefile from being locked. The memory layer also has to be added to the QgsMapLayerRegistry before it could be used in the processing algorithm.

import glob, os, processing

input = "//input.shp"
output = "//output_100.shp"

layer = QgsVectorLayer(input,"any_name","ogr")
feats = [ feat for feat in layer.getFeatures() ]
temp = QgsVectorLayer("LineString?crs=epsg:4326", "result", "memory")
# 'temp' is the new memory layer
# Change 'LineString' to 'Point' or 'Polygon' etc depending on your layer type

temp_data = temp.dataProvider()
attr = layer.dataProvider().fields().toList()
temp_data.addAttributes(attr)
temp.updateFields()
temp_data.addFeatures(feats)
QgsMapLayerRegistry.instance().addMapLayer(temp)
# Adds memory layer with all copied attributes to ToC

interval = 100
processing.runalg("qgis:densifygeometriesgivenaninterval", temp, interval, output)
# Processing algorithm uses memory layer as input parameter

QgsMapLayerRegistry.instance().removeMapLayer(temp.id())
del layer
# Removes from ToC, deletes the dependency on original input shapefile

os.chdir("C:\Users\gfb11209\Desktop\New folder (2)//")
for input_file in glob.glob("input*"):
    os.remove(input_file)
    # Sets current directory to desired folder and removes "input" files

for output_file in os.listdir("."):
    os.rename(output_file, output_file.replace("output_100", "input"))
    # Renames "output_100" files to "input"

(Credit to @Detlev and @xunilk for their very useful answers from this post.)


  • Split script / restart QGIS

You could split your script into two parts. Run the first part to execute the algorithm and once the output has been saved, restart QGIS and run the second part of the script. This way, the input files should no longer be used and can be safely removed.

So your first script could look like:

import processing

input = "//input.shp"
output = "//output_100.shp"
interval = 100

processing.runalg("qgis:densifygeometriesgivenaninterval", input, interval, output)

Restart QGIS and then run:

import os, glob

os.chdir("C:/" + os.getenv('USERNAME') + "/SHP_Path//")
for input_file in glob.glob("input*"):
    os.remove(input_file)    # Removes all files beginning with "input" (eg. input.dbf, input.prj etc)

for output_file in os.listdir("."):
    os.rename(output_file, output_file.replace("output_100", "input"))
4
  • I did the same trick but restarting QGIS to remove a file is not comfortable. I'm waiting for other solution but of course thank you very much for your help and interesting.
    – Artec
    Dec 11, 2015 at 16:38
  • @Artec - Hi buddy, edited my post to include another method which doesn't require restarting QGIS.
    – Joseph
    Dec 16, 2015 at 11:37
  • 1
    @ Joseph this method works great. I am very glad that I could count on your help.
    – Artec
    Dec 16, 2015 at 19:11
  • @Artec - Most welcome buddy! I'm just trying to pass on what others have taught me :)
    – Joseph
    Dec 17, 2015 at 10:12

Your Answer

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

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