os.listdir读取文件夹中文件乱序的方法总结

当使用os.listdir读取包含数字命名的文件时,文件可能会按非预期的顺序排列。一种解决方法是自定义排序函数,考虑文件名中的连续数字部分。文中提供的代码实现了根据数字部分正确排序的功能,通过检查字符串是否为数字,找到连续数字子串并进行比较,从而确保按数字顺序排列文件名。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

os.listdir读取文件夹中文件乱序:

本身文件夹里的图片都是按顺序排放,读取的时候却按照1、10、100···这种读取

问题如下:
在这里插入图片描述

解决方案:

1.我看了很多文章说这段代码可以解决,然而我的不行

dir=''
filenames=os.listdir(dir)
filenames.sort(key=lambda x:int(x[:-4]))

key=lambda 元素: 元素[字段索引]
比如 print(sorted(C, key=lambda x: x[2]))
x:x[]字母可以随意修改,排序方式按照中括号[]里面的维度进行排序,[0]按照第一维排序,[2]按照第三维排序

会出现如下错误:

在这里插入图片描述
如果有解决方法的话,请评论告诉我下。

2.最后我用这段代码解决了问题

代码如下:

import os
 
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))
    continuous_num = ''
    for c in range(0, smaller_length):
        if not is_number(file1[c]) and not is_number(file2[c]):
            # print('both not number')
            if file1[c] < file2[c]:
                return True
            if file1[c] > file2[c]:
                return False
            if file1[c] == file2[c]:
                if c == smaller_length - 1:
                    # print('the last bit')
                    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
            elif find_continuous_num(file1, c) > find_continuous_num(file2, c):
                return False
 
 
    # if file1 < file2:
    #     return True
    # else:
    #     return False
 
def sort_insert(lst):
    for i in range(1, len(lst)):
        x = lst[i]
        j = i
        while j > 0 and lst[j - 1] > x:
            # while j > 0 and comp2filename(x, lst[j-1]):
            lst[j] = lst[j - 1]
            j -= 1
        lst[j] = x
    return lst
 
def sort_insert_filename(lst):
    for i in range(1, len(lst)):
        x = lst[i]
        j = i
        # while j > 0 and lst[j-1] > x:
        while j > 0 and comp2filename(x, lst[j - 1]):
            lst[j] = lst[j - 1]
            j -= 1
        lst[j] = x
    return lst
 
def file_name_sort(all_file_list):
    new_list = []
    return new_list


dir=''
filenames=os.listdir(dir) 
print(sort_insert_filename(filenames))
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值