Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add characters to filename using glob in Python?

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()
like image 589
Joseph Avatar asked Oct 20 '22 17:10

Joseph


2 Answers

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()
like image 195
Anshul Goyal Avatar answered Oct 31 '22 21:10

Anshul Goyal


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)))
like image 27
Padraic Cunningham Avatar answered Oct 31 '22 22:10

Padraic Cunningham