繁体   English   中英

os.rename上遇到“ OSError:[Errno 2]没有这样的文件或目录”

[英]“OSError: [Errno 2] No such file or directory” encountered on os.rename

我在文件夹中存储了许多图像文件,分别存储为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.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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM