按文件基本名称对路径列表进行排序(Python) [英] Sort list of paths by file basename (Python)

查看:590
本文介绍了按文件基本名称对路径列表进行排序(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含图像的文件夹. 我将每个图像的路径添加到列表中.它们不是按字母顺序排序的. 我对该函数进行了排序,但是排序后打印列表时的结果是相同的.

I have a folder with images. I added to a list the paths for each image. They are not alphabetically sorted. I made this function to sort but I the result it's the same when I print the list after sorting.

import os
import glob

images_path = os.path.expanduser('~\\Desktop\\samples\\')

def img_path_list():
    img_list = []
    for file_path in glob.glob(str(images_path) + "*.jpg"):
        img_list.append(file_path)

    img_list.sort(key=lambda x: str(x.split('.')[0]))

    return img_list

print(img_path_list())

结果仍然是[Desktop\\t0.jpg, Desktop\\t1.jpg, Desktop\\t10.jpg, Desktop\\t11.jpg, Desktop\\t2.jpg, ...]

只要我不要求使用natsort模块,而是简单的python,就不会重复.

not a duplicate as long as I didn't request to use natsort module but with simple python.

推荐答案

使用os.path.basename并假设您的文件名都是X#.jpg格式,其中X是单个字符:

Using os.path.basename and assuming your filenames are all of the format X#.jpg with X a single character:

import os

img_list = ['Desktop\\t0.jpg', 'Desktop\\t1.jpg',
            'Desktop\\t10.jpg', 'Desktop\\t11.jpg',
            'Desktop\\t2.jpg']

img_list.sort(key=lambda x: int(os.path.basename(x).split('.')[0][1:]))

print(img_list)

['Desktop\\t0.jpg', 'Desktop\\t1.jpg',
 'Desktop\\t2.jpg', 'Desktop\\t10.jpg',
 'Desktop\\t11.jpg']

使用命名函数来说明lambda的工作方式:

With a named function to illustrate how lambda works:

def sorter(x):
    return int(os.path.basename(x).split('.')[0][1:])

img_list.sort(key=sorter)

说明

这里有一些步骤:

  1. 通过os.path.basename提取文件名.
  2. .分割并提取第一个元素.
  3. 然后从第一个字符开始进行切片.
  4. 将结果转换为int以进行数字排序.
  1. Extract the filename via os.path.basename.
  2. Split by . and extract first element.
  3. Then slice by 1st character onwards.
  4. Convert the result to int for numerical ordering.

这篇关于按文件基本名称对路径列表进行排序(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆