簡體   English   中英

os.rename()文件到文件夾名稱的一部分

[英]os.rename() file to part of folder name

我有多個文件夾,看起來像folder.0folder.1 在每個文件夾中都有一個文件( 'junk' )我要復制並重命名為它當前所在的文件夾名稱的.0.1部分。
這是我正在嘗試做的事情:

inDirec = '/foobar'
outDirec = '/complete/foobar'


for root, dirs,files in os.walk(inDirec):
    for file in files:
        if file =='junk'
            d = os.path.split(root)[1]
            filename, iterator = os.path.splitext(d)  # folder no. captured
            os.rename(file, iterator+file) # change name to include folder no.
            fullpath = os.path.join(root,file)
            shutil.copy(fullpath,outDirec)

返回:

os.rename(file,iterator+file)
OSError: [Errno 2] No such file or directory

我甚至不確定我應該使用os.rename。 我只想提取files == 'junk'並將它們復制到一個目錄,但它們都具有完全相同的名稱。 所以我真的只需要重命名它們,以便它們可以存在於同一目錄中。 有幫助嗎?

更新

    for root, dirs,files in os.walk(inDirec):
    for file in files:
        if file =='junk'
            d = os.path.split(root)[1]
            filename, iterator = os.path.splitext(d)  # folder no. captured
            it = iterator[-1] # iterator began with a '.'

            shutil.copy(os.path.join(root,file),os.path.join(outDirec,it+file))

您的問題是您的程序在啟動時使用工作目錄進行重命名操作。 您需要提供完整的相對或絕對路徑作為os.rename()的參數。

更換:

os.rename(file, iterator+file)
fullpath = os.path.join(root,file)
shutil.copy(fullpath,outDirec)

隨着(如果你想移動):

os.rename(os.path.join(root, file), os.path.join(outDirec, iterator+file))

或者(如果你想復制):

shutil.copy(os.path.join(root, file), os.path.join(outDirec, iterator+file))

注意:目標目錄應該已經存在,或者您將需要代碼來創建它。

暫無
暫無

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

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