繁体   English   中英

递归重命名文件扩展名

[英]Recursively rename file extensions

我在创建一个 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
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 的答案

我稍微修改了 Hector Rodriguez Jr. 的答案,因为它会替换路径中出现的任何".jpg" ,例如/path/to/my.jpg.files/001.jpg会变成/path/to/my.jpeg.files/001.jpeg ,这不是你想要的,对吧?

尽管使用点"."通常不是一个好主意"." 在文件夹名称中,它可能发生...

import os
import sys

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

您可以像这样处理目录:

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将遍历所有顶级和进一步的目录/文件

这样做:

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

那应该完全符合您的要求。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM