python路径列表,按文件基本名称对路径列表进行排序(Python)

该博客探讨了如何对包含数字的图片文件路径进行排序。原始代码使用了Python的`os`和`glob`库来获取图片路径,并尝试通过`lambda`函数对路径中的数字部分进行排序。然而,初始排序并未按数字顺序排列。解决方案是利用`os.path.basename`获取文件名,然后通过切片和转换为整数进行排序。这种方法确保了即使数字前有字符,也能正确排序。
摘要由CSDN通过智能技术生成

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())

The result it's still i.e: [Desktop\\t0.jpg, Desktop\\t1.jpg, Desktop\\t10.jpg, Desktop\\t11.jpg, Desktop\\t2.jpg, ...]

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

解决方案

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']

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)

Explanation

There are a few steps here:

Extract the filename via os.path.basename.

Split by . and extract first element.

Then slice by 1st character onwards.

Convert the result to int for numerical ordering.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值