Python文件排序
按文件名称字符串小写排序
images.sort(key=lambda x: x.lower())
按创建时间精确到秒排序
images.sort(key=lambda x: os.path.getctime(x))
按创建时间,精确到纳秒排序
images.sort(key=lambda x: os.stat(x).st_ctime_ns)
按文件名称去掉后缀的数值名称排序
images.sort(key = lambda x: int(x[:-4]))
使用os.stat的返回值statinfo的三个属性获取文件的创建时间等信息
statinfo=os.stat("E:\\A\\314_noteach_20190315162753_1552638473_152.png")
st_atime (访问时间), st_mtime (修改时间), st_ctime(创建时间)
print(statinfo)
print(statinfo.st_mtime)
print(statinfo.st_ctime_ns)
可按照文件名称排序,对字符串和数值混合的可以自定义实现混合排序
基于字符串数字混合排序的Python脚本:
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
def is_number(s):
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
def find_continuous_num(astr, c):
num = ''
try:
while not is_number(astr[c]) and c < len(astr):
c += 1
while is_number(astr[c]) and c < len(astr):
num += astr[c]
c += 1
except:
pass
if num != '':
return int(num)
def comp2filename(file1, file2):
smaller_length = min(len(file1), len(file2))
for c in range(0, smaller_length):
if not is_number(file1[c]) and not is_number(file2[c]):
if file1[c] < file2[c]:
return True
if file1[c] > file2[c]:
return False
if file1[c] == file2[c]:
if c == smaller_length - 1:
if len(file1) < len(file2):
return True
else:
return False
else:
continue
if is_number(file1[c]) and not is_number(file2[c]):
return True
if not is_number(file1[c]) and is_number(file2[c]):
return False
if is_number(file1[c]) and is_number(file2[c]):
if find_continuous_num(file1, c) < find_continuous_num(file2, c):
return True
else:
return False
def sort_list_by_name(lst):
for i in range(1, len(lst)):
x = lst[i]
j = i
while j > 0 and comp2filename(x, lst[j-1]):
lst[j] = lst[j-1]
j -= 1
lst[j] = x
return lst
本文来自博客园,作者:I'm_江河湖海,转载请注明原文链接:https://www.cnblogs.com/jhhh/p/16762314.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!