简体   繁体   中英

How do I add extensions to files using python in multiple subdirectories

I need to add a .jpg extension to around 300K pictures. They are all in 12 sub-directories and four more subdirectories in each of those 12.

I tried following this post but didn't do a walk down to all subdirectories: Adding extension to multiple files (Python3.5)

I also tried the following:

import os

path = 'C:\\Photos'
genmod = os.walk(path)

for path, pathnames, files in gen_obj:
    for file in files:

        head, tail = os.splitext(file)
        if not tail:
            src = os.path.join(path, pathnames, file)
            dst = os.path.join(path, pathnames, file + '.jpg')

            if not os.path.exists(dst): # check if the file doesn't exist
                os.rename(src, dst)

The above runs but nothing happens.

The above runs but nothing happens.

I doubt that, there are 2 problems:

  • os.splitext should be os.path.splitext
  • os.path.join should not be given pathnames , so

     os.path.join(path, pathnames, file) 

    should be

     os.path.join(path, file) 

    and

     os.path.join(path, pathnames, file + '.jpg') 

    should be

     os.path.join(path, file + '.jpg') 

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