Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在多个子目录中使用python向文件添加扩展名_Python_Python 3.x - Fatal编程技术网

如何在多个子目录中使用python向文件添加扩展名

如何在多个子目录中使用python向文件添加扩展名,python,python-3.x,Python,Python 3.x,我需要添加一个.jpg扩展到大约300K图片。它们都在12个子目录中,在这12个子目录中还有4个子目录 我试着跟随这篇文章,但没有走到所有的子目录: 我还尝试了以下方法: 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)

我需要添加一个.jpg扩展到大约300K图片。它们都在12个子目录中,在这12个子目录中还有4个子目录

我试着跟随这篇文章,但没有走到所有的子目录:

我还尝试了以下方法:

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
    不应指定
    路径名
    ,因此

    os.path.join(path, pathnames, file)
    
    应该是

    os.path.join(path, file)
    

    应该是

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

您确定它可以运行吗?有几个错误。我要说,它没有给出错误消息。如果您应该使用标准库的一部分,而不是使用
os
,我会感到惊讶。
os.path.join(path, file + '.jpg')