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

How to add characters to filename using glob in Python?

以下是一段代码。该脚本从 "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()

您目前计算了一次 output 变量(IMO 无法工作,因为您还没有定义任何 fname)。

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

回答你的问题:

我如何设置它以便输出文件改为读取 "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)))