递归重命名文件扩展名

时间:2016-05-03 21:34:12

标签: python

我很难创建一个python脚本,它将重命名文件夹中的文件扩展名,并继续在子目录中执行此操作。这是我到目前为止的剧本;它只能重命名顶层目录中的文件:

#!/usr/bin/python
# Usage: python rename_file_extensions.py

import os
import sys

for filename in os.listdir ("C:\\Users\\username\\Desktop\\test\\"): # parse through file list in the folder "test"

    if filename.find(".jpg") > 0: # if an .jpg is found

            newfilename = filename.replace(".jpg","jpeg") # convert .jpg to jpeg

            os.rename(filename, newfilename) # rename the file

3 个答案:

答案 0 :(得分:6)

import os
import sys

directory = os.path.dirname(os.path.realpath(sys.argv[0])) #get the directory of your script
for subdir, dirs, files in os.walk(directory):
 for filename in files:
  if filename.find('.jpg') > 0:
   subdirectoryPath = os.path.relpath(subdir, directory) #get the path to your subdirectory
   filePath = os.path.join(subdirectoryPath, filename) #get the path to your file
   newFilePath = filePath.replace(".jpg",".jpeg") #create the new name
   os.rename(filePath, newFilePath) #rename your file

我用文件路径和重命名文件的完整示例修改了Jaron的答案

答案 1 :(得分:1)

您可以像这样处理目录:

import os

def process_directory(root):

    for item in os.listdir(root):
        if os.path.isdir(item):
            print("is directory", item)
            process_directory(item)
        else:
            print(item)
            #Do stuff

process_directory(os.getcwd())

虽然,这不是必需的。只需使用os.walk,它将遍历所有顶层和更多目录/文件

答案 2 :(得分:0)

这样做:

for subdir, dirs, files in os.walk(root):
    for f in files:
        if f.find('.jpg') > 0:
            #The rest of your stuff

这应该完全符合你的要求。