You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python:按自然顺序排序文件名并存入DataFrame

实现自然排序读取文件路径并存入DataFrame

步骤1:获取所有目标文件路径

用Python的glob模块可以快速匹配所有符合格式的文件:

import glob
file_paths = glob.glob('./images/X_0_image*.png')

这行代码会把./images目录下所有以X_0_image开头、.png结尾的文件路径全部获取到。

步骤2:进行自然排序

默认的字符串排序会出现X_0_image100.png排在X_0_image10.png前面的问题,这里提供两种解决方式:

方法一:手动提取数字作为排序键

通过正则表达式从文件名中提取数字部分,转成整数后作为排序依据:

import re

def get_file_number(file_path):
    # 匹配文件名里的数字
    num_match = re.search(r'X_0_image(\d+)\.png', file_path)
    return int(num_match.group(1)) if num_match else 0

sorted_paths = sorted(file_paths, key=get_file_number)

方法二:借助natsort库一键自然排序

如果不想自己写正则逻辑,可以直接用专门处理自然排序的natsort库。先安装库:

pip install natsort

然后调用natsorted函数即可:

from natsort import natsorted
sorted_paths = natsorted(file_paths)

这个函数会自动识别文件名中的数字序列,按照人类习惯的升序排列。

步骤3:存入DataFrame

用pandas将排序后的路径列表转换为DataFrame,默认的索引就是从0开始的,完全符合文件创建时的索引顺序:

import pandas as pd

df = pd.DataFrame({'file_path': sorted_paths})

内容的提问来源于stack exchange,提问作者Zen4ttitude

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 14:30:38