簡體   English   中英

使用 python os.rename 時報錯【183】

[英]Error [183] when using python os.rename

這是我第一次使用 python,我一直遇到錯誤 183。我創建的腳本在 .network 中搜索所有“.py”文件並將它們復制到我的備份驅動器。 請不要嘲笑我的劇本,因為這是我的第一個。

關於我在腳本中做錯了什么的任何線索?

import os
import shutil
import datetime

today = datetime.date.today()
rundate = today.strftime("%Y%m%d")

for root,dirr,filename in os.walk("p:\\"):
    for files in filename:
        if files.endswith(".py"):
            sDir = os.path.join(root, files)
            dDir = "B:\\Scripts\\20120124"
            modname = rundate + '_' + files
            shutil.copy(sDir, dDir)
            os.rename(os.path.join(dDir, files), os.path.join(dDir, modname))
            print "Renamed %s to %s in %s" % (files, modname, dDir)

我猜您正在Windows上運行腳本。 根據Windows錯誤代碼列表,錯誤183為ERROR_ALREADY_EXISTS

因此,我猜該腳本失敗了,因為您試圖在現有文件上重命名文件。

也許您每天運行腳本不止一次? 這將導致所有目標文件都已經存在,因此在腳本多次運行時重命名失敗。

如果您特別想覆蓋文件,則可能應該先使用os.unlink刪除它們。

鑒於錯誤183為[Error 183] Cannot create a file when that file already exists的事實,即[Error 183] Cannot create a file when that file already exists ,您很可能會在os.walk()調用中找到2個同名文件,並在第一個文件成功重命名后,第二個將無法重命名為相同的名稱,因此您將獲得文件已存在錯誤。

我建議在os.rename()調用周圍使用try / except來處理這種情況(在名稱或其他內容后面添加一個數字)。

[是的,我知道問這個問題已經有7年了,但是如果我從Google搜索中來到這里,也許其他地區也能找到它,這個答案可能會有所幫助。]

我只是遇到了同樣的問題,當您嘗試重命名一個文件夾時,該文件夾與同一目錄中存在的文件夾具有相同的名稱,Python 將引發錯誤。

如果您嘗試在 Windows Explorer 中執行此操作,它會詢問您是否要合並這兩個文件夾。 但是,Python 沒有此功能。

下面是我的代碼實現重命名文件夾的目的,而同名文件夾已經存在,這實際上是合並文件夾。

import os, shutil

DEST = 'D:/dest/'
SRC = 'D:/src/'

for filename in os.listdir(SRC):  # move files from SRC to DEST folder.
    try:
        shutil.move(SRC + filename, DEST)
    # In case the file you're trying to move already has a copy in DEST folder.
    except shutil.Error:  # shutil.Error: Destination path 'D:/DEST/xxxx.xxx' already exists
        pass

# Now delete the SRC folder.
# To delete a folder, you have to empty its files first.
if os.path.exists(SRC):
    for i in os.listdir(SRC):
        os.remove(os.path.join(SRC, i))
    # delete the empty folder
    os.rmdir(SRC)

暫無
暫無

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

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