尝试仅将不同相机型号的上次写入时间(上次文件内容修改时间)时间戳附加到选择媒体文件类型的文件名中。模式为: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
最佳答案
您的代码中有一些小拼写错误
1. 第 5 行应该是 'g7'
而不是 'ng7'
2. convert_time_to_ human_可读
仅在get_last_write_time(filename)
中定义,不能在其外部使用。
3. 倒数第二行缺少 ,
。
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))
关于python - 根据文件类型为文件名添加 LasWriteTime 前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47259989/