2

I would like to rename all output files after my script has finished processing them by adding "(A)" after their file name (eg. Layer.shp -> Layer (A).shp). I received an answer from this post on the commands required to rename files. I put this at the end of the script but I receive the following message when running the script:

WindowsError: [Error 32] The process cannot access the file because it is being used by another process: 'Layer.dbf'

I thought I closed the related processes associated with QGIS but it seems not. The following is a snippet:

import os, sys, glob, shutil
from qgis.core import *
from qgis.gui import QgsMapCanvas
from PyQt4.QtGui import *
from os.path import expanduser
home = expanduser("~")
# Folder path of the Results for shapefiles
path_dir = home + "\Desktop\Test\\"
path_res = path_dir + "Results\\"
Cellsize = 200
layerPath = path_dir + "Layer.shp"
extent = QgsVectorLayer( layerPath, '', 'ogr' ).extent()
centerx = (extent.xMinimum() + extent.xMaximum()) / 2
centery = (extent.yMinimum() + extent.yMaximum()) / 2
width = extent.xMaximum() - extent.xMinimum()
height = extent.yMaximum() - extent.yMinimum()
def run():
 outputs_0=general.runalg("qgis:creategrid", Cellsize, Cellsize, width, height, centerx, centery, 1, 'EPSG:7405', None)
 # Set directory and search for all polygon shapefiles 
 os.chdir(path_dir + "Polygon Shapefile\\")
 for fname in glob.glob("*.shp"):
 # Clip .shp files within directory to Grid and save files to Result folder 
 outputs_1=general.runalg("qgis:clip", outputs_0['SAVENAME'], fname, path_res + "/" + fname)
# Paths of the shapefiles in the Result folder with list comprehension
 output = [shp for shp in glob.glob(path_res + "*.shp")]
run()
QgsApplication.exitQgis()
app.exit()
os.chdir(path_res)
for fname in glob.glob("*.*"):
 name,ex = fname.rsplit(".",1)
 shutil.move(fname,os.path.join(path_res,"{}{}{}".format(name," (A).",ex)))
PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Feb 24, 2015 at 12:16

1 Answer 1

4

Have you tried adding the "(A)" before passing the output parameter to the algorithm? You would need to add 3 lines to the for loop in the run() method:

for fname in glob.glob("*.shp"):
 pieces = list(os.path.splitext(fname))
 pieces.insert(1,"(A)")
 nameWithA = "".join(pieces)
 outputs_1=general.runalg("qgis:clip", outputs_0['SAVENAME'], fname, path_res + "/" + nameWithA)
answered Feb 24, 2015 at 12:44
0

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.