如何在Python中使用glob将字符添加到文件名?

时间:2015-02-20 15:00:27

标签: python character glob qgis

以下是一段代码。该脚本从“Test”文件夹中获取输入文件,运行一个函数,然后在“Results”文件夹中输出具有相同名称的文件(即"Example_Layer.shp")。我如何设置它以便输出文件将而是阅读"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()

2 个答案:

答案 0 :(得分:2)

您目前计算output变量一次(由于您尚未定义任何fname,因此IMO无效)。

在for循环中移动计算输出变量的语句,如下所示:

#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()

答案 1 :(得分:1)

回答你的问题:

如何设置它以便输出文件改为" Example_Layer(A).shp"

您可以使用shutil.copy将文件复制到新目录,使用"(A)"为每个文件名添加os.path.join以加入路径和新文件名:

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