首页 > 解决方案 > 使用 glob.glob 设置顺序

问题描述

我想在我的脚本打开文件时设置自己的顺序,但 glob.glob 默认打开文件是随机的。

我有以下文件:'fish.txt'、'expo.txt'、'random.txt'。

这是我所有文件的小规模示例,我想设置我的顺序。

我已经编写了使用 glob.glob 打开文件的常规方法

#! /usr/bin/env python
import sys, os, glob
mylist = ['fish.txt','random.txt', 'expo.txt']
def sorter(item):
    for item in mylist:
        return item

for file in sorted(glob.glob('*.txt'), key = sorter):
     print(file)

我想要的输出是:

鱼.txt

随机.txt

世博会.txt

标签: pythonfunctionsortingglob

解决方案


您可以sorted(list)在迭代之前对文件名进行排序:

#!/usr/bin/env python
import sys, os, glob

def sorter(item):
    """Get an item from the list (one-by-one) and return a score for that item."""
    return item[1]

files = sorted(glob.glob('*.txt'), key=sorter)
for file in files:
     print(file)

在这里,它按文件名中的第二个字母排序。将函数更改为sorter()您想要对文件列表进行排序的方式。

要按字母顺序排序,您不需要该key=sorter部分,因为这是sorted()字符串列表的默认行为。那么它会变成:

files = sorted(glob.glob('*.txt'))
for file in files:
     print(file)

推荐阅读