繁体   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