7

I've looked at some answers on here about deleting shapefiles with QGIS but I still seem to be running into errors. I am trying to delete shapefiles that have no attribute data in them (so 0 rows). My main issue is that I get:

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process:

I have tried using QgsVectorFileWriter.deleteShapeFile(f) but that leaves the .shp and .dbf behind.

I have also tried using os.remove for each individual file extension and that gives me the Win Error 32.

It seems like my files are still being used in QGIS. Does anyone know how to work around it?

Here is my full script:

clipped_soilpoly = get_data(clipped_folder, ".shp") # makes a list of all the .shps
for f in clipped_soilpoly:
    shapelayer = QgsVectorLayer(f,"clipped_poly")
    rowcount = shapelayer.featureCount()`

if rowcount < 1: 

            print ("deleting " + f + " - does not intersect")

        #QgsVectorFileWriter.deleteShapeFile(f) <-- only deleting some of the file extensions

            split_path = os.path.splitext(f)[0]
            del f

        #delete .shp
            shp = split_path + ".shp"
            os.remove(shp)

        #delete .dbf    
            dbf = split_path + ".dbf"
            os.remove(dbf)

        #delete .prj    
            prj = split_path + ".prj"
            os.remove(prj)

        #delete .qpj    
            qpj = split_path + ".qpj"
            os.remove(qpj)

        #delete .shx   
            shx = split_path + ".shx"
            os.remove(shx)


        else:
            print ("keeping " + f)

4 Answers 4

5

On Windows you must stop using and close the file before you can delete it. So QgsVectorFileWriter.deleteShapeFile(f) will work, once you have let go of the file which is still being used by shapelayer.

The QgsVectorLayer is a wrapper around an OGR C++ call so the easiest way to dispose of it is to set it to None.

clipped_soilpoly = get_data(clipped_folder, ".shp") # makes a list of all the .shps
for f in clipped_soilpoly:
    shapelayer = QgsVectorLayer(f,"clipped_poly")
    rowcount = shapelayer.featureCount()

    if rowcount < 1:
        shapelayer = None
        QgsVectorFileWriter.deleteShapeFile(f)

should work.

1
  • 3
    I have an issue : .prj, .qpj and .shx are deleted but .shp and .dbf remain. Any ideas ? I'm using QGIS 3.10.2
    – GeoGyro
    Commented Apr 7, 2020 at 12:53
0

I used layer.getFeature(1) or layer.getFeatures() and this answer solved my problem using a temporary layer for that functions How to replace a shapefile name in a directory using Python QGIS?

And deleting only locals except variables used further by that answer Deleting variables from the Python Console in a programmatic way?

And at the eof deleting the files using QgsVectorFileWriter.deleteShapeFile()

update: instead of feats=[feat for feat in layer.getFeatures()] supposed in the above link write feats=layer.getFeatures() and del(layer) at the end (deleting locals is not nescessary) otherwise error 32 occured. This solved error 32 for me iterating over layers and appending features instead of using merged_layers=processing.run("qgis:mergevectorlayers", {'LAYERS':layers .. (or layers_paths)

0

One dirty workaround would be to:

  1. Try to delete the file
  2. If it doesn't work, add it to a list of files to delete later
try:
    os.remove(filename_to_delete)
except PermissionError as e:
    with open('files_to_delete.txt', 'a') as list_file:
        # Append to the list
        list_file.write(filename_to_delete + '\n')
  1. At the next opportunity (click of a button, or other event), delete the files marked for deletion
not_deleted_yet = []
with open('files_to_delete.txt', 'r') as list_file:
    for line in list_file:
        filename_to_delete = line.strip()
        # TODO : Here, add a security check, to ensure it's a file you've
        # created, and not an unrelated file
        if not os.path.isfile(filename_to_delete):
            break
        try:
            os.remove(filename_to_delete)
        except PermissionError as e:
            # Still not deleted
            not_deleted_yet.append(line)
with open('files_to_delete.txt', 'w') as list_file:
    # The list file is open in write mode (and is now empty)
    for filename_to_delete in not_deleted_yet:
        # Add this item to the list again
        list_file.write(filename_to_delete + '\n')

0

This option from "The PyQGIS 3.28 Developer Cookbook" works for me:

#To disconnect from QGIS to remove all shapefiles (and its auxiliary files)
QgsApplication.exitQgis() #====This is from de Cookbook====
file_list= os.listdir(folder_with_files)
for my_file in file_list:
  os.remove(folder_with_files + my_file)

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.