gpt4 book ai didi

python - 递归重命名文件扩展名

转载 作者:太空宇宙 更新时间:2023-11-04 07:35:30 24 4
gpt4 key购买 nike

我很难创建一个 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 的回答

关于python - 递归重命名文件扩展名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37014760/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com