优化python中os模块遍历文件夹时的排序问题

优化前:

import os

for file in os.listdir('draft'):
    print(file)

结果:
在这里插入图片描述

优化后:

def string20(txt,width=20):
    """
    对字符串内的数字前添加n个'0',n = width - 数字长度, 如:-1-2-  ->  -00000000000000000001-00000000000000000002-
    该函数主要应用于更正 os模块遍历文件时的排序方式。
    :param txt: 原始字符串
    :param width: 处理后的数字长度
    :return: 处理后的字符串
    """
    result = ''
    digital = ''
    for s in txt:
        if s.isdigit():
            digital += s
        else:
            if len(digital) == 0:
                result += s
            else:
                result += '0'*(width-len(digital)) + digital + s
                digital = ''
    if len(digital)!=0:  # 当字符串末尾是数字时,循环结束后要单独再处理
        result += '0' * (width - len(digital)) + digital + s
    return result

import os
for file in sorted(os.listdir('draft'),key=string20):
    print(file)

结果:
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值