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