2015-12-04 47 views
0

我有一些图像文件存储为0.png,1.png,...,x.png在一个文件夹中。我必须以相反的顺序重新命名,即0-> x,1->(x-1),...,(x-1) - > 1,x-> 0。我已经在python中编写了下面的代码。“OSError:[Errno 2]没有这样的文件或目录”遇到os.rename

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 

我在做什么错? 有没有更智能的方法呢?

+1

也许在中间的一个文件丢失。您应该捕获“OSError”并将其与受影响的文件名一起打印出来。 – glglgl

+0

我只用两个文件就试过了,当调用os.rename时它失败。 – nirupma

+0

尝试使用'os.path.exists'来检查您的文件是否存在 –

回答

2

请尝试以下操作,它使用glob模块获取文件列表。这应该包括完整路径,否则os.rename可能失败:

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文件,你可以改变水珠线为*.png

+0

感谢martin !!! – nirupma

+0

@Martin ..“os.rename”需要一个完整的路径名吗? –

+1

不,但强烈建议使用一个,否则您依赖当前目录。 –

相关问题