在上遇到“OSError:[Errno 2]没有这样的文件或目录”操作系统重命名

2024-09-27 07:29:54 发布

您现在位置: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" + str(x) + ".png"
    newname = str(maxx-x) + ".png"
    os.rename(tempname, newname)

我遇到了以下错误:

^{pr2}$

我做错什么了? 有没有更聪明的方法?在


Tags: ingt文件夹forpng顺序os图像文件
1条回答
网友
1楼 · 发布于 2024-09-27 07:29:54

尝试下面的方法,它使用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文件为目标,可以将glob行改为*.png

相关问题 更多 >

    热门问题