我需要为30万张图片添加.jpg扩展名。它们全部位于12个子目录中,并且在这12个子目录中又有四个子目录。

我尝试关注此帖子,但没有深入了解所有子目录:
Adding extension to multiple files (Python3.5)

我还尝试了以下方法:

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)


以上运行,但没有任何反应。

最佳答案

以上运行,但没有任何反应。


我怀疑有两个问题:


os.splitext应该是os.path.splitext
os.path.join不应该被赋予pathnames,所以

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


应该

os.path.join(path, file)




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


应该

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

关于python - 如何在多个子目录中使用python向文件添加扩展名,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57999039/

10-11 15:23