如何将文件名更改为整数,以便以后创建的文件使用更大的数字命名?

问题描述 投票:0回答:1

我为自己制作了一个脚本,该脚本每2秒下载一次图片并将其放入文件夹中。现在,我希望下载的第一张图片命名为“ 1”,第二张图片命名为“ 2”,依此类推。它可以从“ 0”开始。那不是很重要。我猜错误在于getctime,因为排序某种程度上搞砸了。

因为我对文件进行了排序,所以os.listdir随机顺序无关紧要。我不认为我搞砸了lambda函数,但是目前我很茫然。我尝试使用getmtime,但也不起作用。

程序结果是这样的:https://i.imgur.com/duMBDa1.png分配的数字看似随机。将Ctime保存在file_data_list中之前,不应更改它。Count + extension可能会引发错误,但是很容易解决。我尝试在13分钟内下载的450张图片上运行此操作,每张图片之间间隔2秒,因此ctime属性的分辨率应该不是问题。

import os

filelist = os.listdir('./')
# get the list of all files in the directory and sort them after creation time
file_date_list = sorted(filelist, key=lambda x: os.path.getctime(x))

# go through the sorted list and rename them
for count,file in enumerate(file_date_list):
    filename, extension = os.path.splitext(file)
    os.rename(file, count+extension)
input()
python sorting integer file-rename creation
1个回答
0
投票

将提供帮助:

for count,file in enumerate(file_date_list):
    filename, extension = file.split('.')
    os.rename(file, str(count)+extension)
© www.soinside.com 2019 - 2024. All rights reserved.