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

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

解决方法:

回答你的问题:

我怎么能设置它,以便输出文件改为“Example_Layer(A).shp”

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

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)))
上一篇:在Ubuntu上编译QGIS 3.6.*-3.10.* 代码的填坑笔记


下一篇:Linux的运维之旅第一天