The following is a snippet of code. The script takes the input files from a "Test" folder, runs a function and then outputs the files with the same name in the "Results" folder (i.e. "Example_Layer.shp")
. How could I set it so that the output file would instead read "Example_Layer(A).shp"
?
#Set paths
path_dir = home + "\Desktop\Test\\"
path_res = path_dir + "Results\\"
def run():
#Set definitions
input = path_res + "/" + "input.shp"
output = path_res + "/" + fname
#Set current path to path_dir and search for only .shp files then run function
os.chdir(path_dir)
for fname in glob.glob("*.shp"):
run_function, input, output
run()
You currently calculate the output
variable once (which IMO wouldn't work since you don't have any fname
defined yet).
Move the statement where you compute the output variable within the for loop, like below:
#Set paths
path_dir = home + "\Desktop\Test\\"
path_res = path_dir + "Results\\"
def run():
#Set definitions
input = path_res + "/" + "input.shp"
#Set current path to path_dir and search for only .shp files then run function
os.chdir(path_dir)
for fname in glob.glob("*.shp"):
output = path_res + "/" + fname
run_function, input, output
run()
To answer your question:
How could I set it so that the output file would instead read "Example_Layer(A).shp"
You can use shutil.copy to copy the file to the new directory, adding a "(A)"
to each file name using os.path.join
to join the path and new filename:
path_dir = home + "\Desktop\Test\\"
path_res = path_dir + "Results\\"
import os
import shutil
def run():
os.chdir(path_dir)
for fname in glob.glob("*.shp"):
name,ex = fname.rsplit(".",1) # split on "." to rejoin later adding a ("A")
# use shutil.copy to copy the file after adding ("A")
shutil.copy(fname,os.path.join(path_res,"{}{}{}".format(name,"(A)",ex)))
# to move and rename in one step
#shutil.move(fname,os.path.join(path_res,"{}{}{}".format(name,"(A)",ex)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With