尝试将最后写入时间(上次文件内容修改时间)时间戳添加到来自不同相机型号的选择媒体文件类型的文件名中。模式为:YYYYMMDD_HHMMSS__origfilename.ext
。
例如,之前和 重命名之后:
origfilename.jpg > 20011231_235959__origfilename.jpg
origfilename2.png > origfilename2.png #.txt is not a "media_file"
时间戳的文件类型在嵌套字典中定义,并使用config[camID]["media_file"]
为每种摄像机类型调用:
代码(最后一行给出了语法错误):
config = {
'nd5': {},
'g7': {},
'alpha9': {},
}
config['nd5']['media_file'] = ('nef', 'jpg', 'avi')
config['g7']['media_file'] = ('cr2', 'jpg', 'mp4')
config['alpha9']['media_file'] = ('jpg')
root = "."
def get_last_write_time(filename):
st = os.stat(filename)
convert_time_to_human_readable = time.strftime("%Y%m%d_%H%M%S", time.localtime(st.st_mtime))
return convert_time_to_human_readable
timestr = convert_time_to_human_readable
for camID in config:
for dir in next(os.walk(root))[1]:
if dir.endswith(camID):
for path, dirs, files in os.walk(os.path.join(root, dir)):
for f in files:
if any([f.lower().endswith(x) for x in config[camID]["media_file"]]):
os.rename(os.path.join(path, f)
os.path.join(path, "%s" % timestr+'_'+f))
显示= camID(= key1,目录名称中最后一个=
之后的字符串)的树以及要附加时间戳的文件类型:
└───CWD
├───001=nd5
│ └───DCIM
│ ├───125NCD5 ('nef', 'jpg', 'avi')
│ ├───126NCD5 ('nef', 'jpg', 'avi')
│ └───127NCD5 ('nef', 'jpg', 'avi')
├───002=nd5
│ └───DCIM
│ ├───201NCD5 ('nef', 'jpg', 'avi')
│ ├───202NCD5 ('nef', 'jpg', 'avi')
│ └───203NCD5 ('nef', 'jpg', 'avi')
├───003=g7
│ └───DCIM
│ ├───112___09 ('cr2', 'jpg', 'mp4')
│ └───112___10 ('cr2', 'jpg', 'mp4')
└───004=alpha9
├───DCIM
│ └───101MSDCF ('jpg')
└───PRIVATE
├───AVCHD
│ └───BDMV
│ ├───CLIPINF
│ ├───PLAYLIST
│ └───STREAM
└───SONY
答案 0 :(得分:1)
您的代码中存在小的拼写错误
1.在第5行,它应该是'g7'
而不是'ng7'
2. convert_time_to_human_readable
仅在get_last_write_time(filename)
中定义,不能在其外使用
你在倒数第二行错过,
4.不要在最后一行使用timestr
,而应使用get_last_write_time(f)
import os
config = {
'nd5': {},
'g7': {},
'alpha9': {},
}
config['nd5']['media_file'] = ('nef', 'jpg', 'avi')
config['g7']['media_file'] = ('cr2', 'jpg', 'mp4')
config['alpha9']['media_file'] = ('jpg')
root = "."
def get_last_write_time(filename):
st = os.stat(filename)
convert_time_to_human_readable = time.strftime("%Y%m%d_%H%M%S", time.localtime(st.st_mtime))
return convert_time_to_human_readable
for camID in config:
for dir in next(os.walk(root))[1]:
if dir.endswith(camID):
for path, dirs, files in os.walk(os.path.join(root, dir)):
for f in files:
if any([f.lower().endswith(x) for x in config[camID]["media_file"]]):
os.rename(os.path.join(path, f),os.path.join(path, "%s" % get_last_write_time(os.path.join(path, f))+'_'+f))