[英]How can i adjust my code to start with a new number?
import os
src = "/home/user/Desktop/images/"
ext = ".jpg"
for i,filename in enumerate(os.listdir(src)):
# print(i,filename)
if filename.endswith(ext):
os.rename(src + filename, src + str(i) + ext)
print(filename, src + str(i) + ext)
else :
os.remove(src + filename)
this code will rename all the images in a folder starting with 0.jpg,1.jpg etc... and remove none jpg but what if i already had some images in that folder, let's say i had images 0.jpg, 1.jpg, 2.jpg, then i added a few others called im5.jpg and someImage.jpg. 此代码将重命名文件夹中以0.jpg,1.jpg等开头的所有图像,并且不删除任何jpg,但是如果我已经在该文件夹中包含一些图像,那么假设我有图像0.jpg,1。 jpg,2.jpg,然后我添加了其他几个,分别称为im5.jpg和someImage.jpg。
What i want to do is adjust the code to read the value of the last image number, in this case 2 and start counting from 3 . 我想要做的是调整代码以读取最后一个图像编号的值,在这种情况下为2,然后从3开始计数。 In other words i'll ignore the already labeled images and proceed with the new ones counting from 3. 换句话说,我将忽略已标记的图像,并继续从3开始计数。
Terse and semi-tested version: 简洁的半测试版本:
import os
import glob
offset = sorted(int(os.path.splitext(os.path.basename(filename))[0])
for filename in glob.glob(os.path.join(src, '*' + ext)))[-1] + 1
for i, filename in enumerate(os.listdir(src), start=offset):
...
Provided all *.jpg files consist of a only a number before their extension. 提供的所有* .jpg文件在扩展名前仅包含一个数字。 Otherwise you will get a ValueError
. 否则,您将得到ValueError
。
And if there happens to be a gap in the numbering, that gap will not be filled with new files. 而且,如果在编号上恰好有间隔,则该间隔将不会填充新文件。 Eg, 1.jpg, 2.jpg, 3.jpg, 123.jpg will continue with 124.jpg (which is safer anyway). 例如,1.jpg,2.jpg,3.jpg,123.jpg会继续显示124.jpg(无论如何还是比较安全)。
If you need to filter out filenames such as im5.jpg or someImage.jpg, you could add an if-clause to the list comprehension, with a regular expression: 如果您需要过滤掉诸如im5.jpg或someImage.jpg之类的文件名,则可以使用正则表达式将if子句添加到列表推导中:
import os
import glob
import re
offset = sorted(int(os.path.splitext(os.path.basename(filename))[0])
for filename in glob.glob(os.path.join(src, '*' + ext))
if re.search('\d+' + ext, filename))[-1] + 1
Of course, by now the three lines are pretty unreadable, and may not win the code beauty contest. 当然,到现在为止,这三行代码还不太可读,可能无法赢得代码选美大赛。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.