簡體   English   中英

如何在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變量一次(由於您尚未定義任何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()

回答你的問題:

我怎么能設置它,以便輸出文件改為“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)))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM