简体   繁体   中英

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.

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 . In other words i'll ignore the already labeled images and proceed with the new ones counting from 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. Otherwise you will get a 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).


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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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