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
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值