5

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()
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
Joseph
  • 586
  • 1
  • 13
  • 32

2 Answers2

2

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()
Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
  • This is correct. Stylistically, I'd also suggest using string substitution as opposed to string concatenation. – ajdigregorio Feb 20 '15 at 15:06
  • Thank you very much for this, I have re-structured my script. However, I accepted the other answer as it focused on how to rename the file (I perhaps should have re-worded the question better so apologies for that). – Joseph Feb 20 '15 at 15:27
1

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)))
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321