简体   繁体   中英

Rename files with names from a list in python

I have a bunch of files that I got into python with :

def list_files(path):
    # returns a list of names (with extension, without full path) of all files 
    # in folder path
    files = []
    for name in os.listdir(path):
        if os.path.isfile(os.path.join(path, name)):
            files.append(name)
    return files 

images = list_files('.')

>>> images
['file1.jpg', 'file2.jpg', 'file3.jpg']

I also have a list like :

>>> b
['ren', 'sans', 'ren']

I wan't to rename images and append the corresponding strings in b, so to get :

file1-ren.jpg
file2-sans.jpg
file3-ren.jpg

for imgs in images :
    os.rename(imgs,''.join(imgs + b for f in b))

TypeError: cannot concatenate 'str' and 'numpy.ndarray' objects

Am I thinking this alright ? Thanks

The idea would be more like:

for img, extra in zip(images, b) :
    os.rename(img, ''.join([img, '-', extra, '.jpg'])

However, it means that you have already removed the extension from img.

If not, then:

for img, extra in zip(images, b) :
    filename, extension = os.path.splitext(img)
    os.rename(img, ''.join([filename, '-', extra, extension])

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