Python &引用;OSError:[Errno 2]没有这样的文件或目录";在os.rename上遇到错误

Python &引用;OSError:[Errno 2]没有这样的文件或目录";在os.rename上遇到错误,python,Python,我有许多图像文件以0.png、1.png、…、x.png的形式存储在一个文件夹中。我必须以相反的顺序重命名,即0->x,1->(x-1),…(x-1)->1,x->0。我已经用python编写了以下代码 for filename in os.listdir("."): tempname = "t" + filename os.rename(filename, tempname) for x in range(minx, maxx+1): tempname = "t" +

我有许多图像文件以0.png、1.png、…、x.png的形式存储在一个文件夹中。我必须以相反的顺序重命名,即0->x,1->(x-1),…(x-1)->1,x->0。我已经用python编写了以下代码

for filename in os.listdir("."):
    tempname = "t" + filename
    os.rename(filename, tempname)
for x in range(minx, maxx+1):
    tempname = "t" + str(x) + ".png"
    newname = str(maxx-x) + ".png"
    os.rename(tempname, newname)
我遇到以下错误:

OSError: [Errno 2] No such file or directory
我做错了什么?
有更聪明的方法吗?

试试下面的方法,它使用
glob
模块获取文件列表。这应该包括完整路径,否则
os。重命名
可能会失败:

import glob
import os

source_files = glob.glob(r'myfolder\mytestdir\*')
temp_files = ['{}.temp'.format(file) for file in source_files]
target_files = source_files[::-1]

for source, temp in zip(source_files, temp_files):
    os.rename(source, temp)

for temp, target in zip(temp_files, target_files):
    os.rename(temp, target)

注意,如果你想瞄准<代码> .png<代码>文件,你可以更改GLUB行为“代码> *.PNG

”,中间可能有一个文件丢失了。您应该捕获

OSError
,并将其与受影响的文件名一起打印。我只对两个文件进行了尝试,调用os.rename时失败。请尝试使用
os.path.exists
检查您的文件是否存在not@Martin ..
os.rename
是否需要完整的路径名?否,但强烈建议使用完整的路径名,否则您将依赖于当前目录的内容。