簡體   English   中英

os.rename() 給出錯誤 FileNotFoundError: [WinError 2] The system cannot find the file specified: '0.jpg' -> '2.jpg'

[英]os.rename( ) is giving the error FileNotFoundError: [WinError 2] The system cannot find the file specified: '0.jpg' -> '2.jpg'

我正在嘗試使用 Python 將文件夾中的每個圖像文件重命名為1.jpg2.jpg等名稱。 我已經編寫了以下代碼,但它不工作,它給出了以下錯誤:

FileNotFoundError: [WinError 2] The system cannot find the file specified: '0.jpg' -> '2.jpg'

代碼:

import os
# changing the directory to where the image files are located
os.chdir(r"F:\Images\7 WONDER GARDEN")

for file in os.listdir():
    for num in range(len(os.listdir())):
        os.rename(file, str(num) + ".jpg")

我嘗試在os.rename中編寫路徑,但仍然給出相同的錯誤。 請幫助我擺脫這個問題。 感謝您努力閱讀此問題。

您正在重命名一個文件len(os.listdir())次,因此第一個內部for循環迭代將起作用,但一旦原始文件不再存在,它將不再起作用。 嘗試以下操作:

import os
# changing the directory to where the image files are located
os.chdir(r"F:\Images\7 WONDER GARDEN")

for index, file in enumerate(os.listdir()):
    os.rename(file, str(index) + ".jpg")

您在這里有雙循環,因此您嘗試將第一個文件重命名為0.jpg ,然后重命名為1.jpg等等。 當然,第一次重命名后,就不能再重命名了。 你真正想要的是:

for num, file in enumerate(os.listdir()):
    os.rename(file, str(num) + ".jpg")

如前所述,導致問題的原因是雙for循環。 內部for循環嘗試一遍又一遍地重復更改文件的名稱,但是一旦該文件的名稱第一次更改,就無法再找到它。

Pythonic 的解決方案是使用名為enumerate()的 function 。 enumerate()返回成對項目的序列:一個索引和一個來自您輸入enumerate()的序列中的項目。

在我們的例子中,文件名列表進入enumerate()並且一系列索引和文件名對出現......

(0, a.jpg)
(1, b.jpg)
(2, c.jpg) 

將此應用於您的代碼...如果您在for循環中使用兩個目標變量而不是一個(在本例中為numfilefor循環將自動解壓縮 enumerate 返回的值,一次一對並在for循環,然后您可以使用值對來幫助文件重命名,如下所示。

for num, file in enumerate(os.listdir()):
    os.rename(file, str(num) + ".jpg")

有趣的是,可以使用 start 參數將 enumerate 設置為從任何初始起點開始的 output 值:

for pair in enumerate(files, 1000):

最終會產生如下所示的配對值:

(1000, a.jpg)
(1001, b.jpg)
(1002, c.jpg) 

嘗試這個

num = 0
for file in os.listdir():
    os.rename(file,str(num) + ".jpg")
    num = num+1

暫無
暫無

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

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