python - 使用 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
解决方案
您可以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)
推荐阅读
- c# - 返回任务
> 从没有等待的 EF Core 查询? - java - 如何使用来自其他项目的模块的 Maven 配置文件
- php - 5.6 和 7.0 中 htmlentities 的 PHP 问题
- sql - 包含分隔列的导入 CSV 数据集的规范化
- selenium - Selenium 脚本抛出异常为 org.openqa.selenium.UnhandledAlertException,即使没有警报
- android-studio - 我无法在 android studio 的 xml 文件的设计选项卡中预览我的应用程序
- exception - 当应用程序在 Android 中崩溃时,Xamarin.Forms 记录异常
- c# - 在 Startup.cs .net core 2.1 中加载程序集
- node.js - 读取文件和将字符串推送到缓冲区有什么区别?- 节点
- wordpress - 如何在wordpress中将注册表滑出到下一个?