如何在所有子文件夹中(在python中)应用脚本进行文件修改?
我创建了一个小脚本来重命名一些图片,但是我的程序只更改脚本文件夹中的图片,而不更改子文件夹中的图片。
from PIL import Image
from os import *
import sys
from os.path import basename
import os
#from PIL.ExifTags import TAGS
from datetime import datetime
extension = ''
#path='/home/pi/Desktop/testrename'
folder_path = "/home/pi/Desktop/testrename/"
l=[]
import PIL.Image
from os import walk
#from path import path
import glob
EXIF_DATETIME = 36867
def renamefinaljpeg() :
glob.glob ('*/.jpeg')
if len(fname) < 20 :
try :
old = PIL.Image.open(fname)._getexif()[EXIF_DATETIME]
old2 = old.split(' ')
os.rename (fname, "yes" + old2[0]+' '+fname)
print('fait')
except :
pass
print('pas jpeg')
def renamefinaljpg() :
glob.glob ('*/.jpg')
if len(fname) < 20 :
try :
old = PIL.Image.open(fname)._getexif()[EXIF_DATETIME]
old2 = old.split(' ')
os.rename (fname, "yes" + old2[0]+' '+fname)
print('fait')
except :
pass
print('pas jpg')
rootDir = "/home/pi/Desktop/testrename/"
for dirName, subdirlist, fileList in os.walk(rootDir) :
for fname in fileList :
print(fname)
try :
renamefinaljpg() or renamefinaljpeg()
except :
pass
print('passe')
在主目录中重命名了映像,但在目录树中未重命名(但已读取) 谢谢您的帮助。
答案 0 :(得分:0)
您似乎已经对如何在脚本中执行操作有很多想法。让我们使用os.walk
,因为这可能是最简单的。 os.walk
将递归遍历所有目录,并为我们提供每个目录中包含的文件名列表。要将文件仅过滤到.jpg
,我们可以使用fnmatch.fnmatch
。
import fnmatch
import os
import sys
from PIL import Image
folder_path = '/home/pi/Desktop/testrename/old'
# Give special numbers a specific name so it's easier to remember what it
# actually means.
EXIF_DATETIME = 36867
def renamefinal(dir_path, filename):
try:
old = Image.open(file_path)._getexif()[EXIF_DATETIME]
date, time = old.split(' ', maxsplit=1)
new_filename = date + ' ' + filename
os.rename(
# Source file name, including directory and filename
os.path.join(dir_path, filename),
# Destination file name, including date
os.path.join(dir_path, new_filename))
print(
'jpg renommé ({}): {} to {}'.format(
dir_path, filename, new_filename))
except:
# Including filename in our output so we know what to check if
# something goes wrong.
print('pas jpg ({}): {}'.format(dir_path, filename))
for path, dirs, files in os.walk(folder_path):
for filename in files:
if not fnmatch.fnmatch(filename, '*.jpg'):
# Go to the next file, skipping the rest of the loop for this file.
continue
if 30 <= len(filename):
continue
renamefinal(path, filename)
更多可能有帮助的