簡體   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