当我的脚本打开文件时,我想设置我自己的顺序,但glob.glob默认的打开文件是随机的。
我有以下文件:‘files.txt’,'expo.txt',‘androm.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)我想要的输出是:
fish.txt
random.txt
expo.txt
发布于 2019-01-07 16:29:52
在迭代文件名之前,可以使用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)发布于 2019-01-07 16:29:38
您可以对glob中的条目进行排序。您可以使用默认排序或选择自己的算法:
的简单用法:
#! /usr/bin/env python
import sys, os, glob
for file in sorted(glob.glob('*.txt')):
print(file)“排序”手册: https://python-reference.readthedocs.io/en/latest/docs/functions/sorted.html
发布于 2019-12-29 23:09:42
您可以结合使用lambda function和sorted(list)来设计您的自定义排序方法。
mylist = ['fish.txt','random.txt', 'expo.txt']
mylist2 = sorted(mylist, key = lambda x: x[-6:-5])
print(mylist2)
#output:
#['random.txt', 'expo.txt', 'fish.txt']这将根据string的自定义参数对列表进行排序。这将使用第6个字符进行排序。
glob.glob()会给你列表,你可以很容易地实现它。
用于从文件夹中读取多个图像。如果您文件名顺序如下: files0.txt、file1.txt、file10.txt、file100.txt、file2.txt,则
sorted(mylist, key = lambda x: x[4:-4]) will help you.您需要存储
()函数的值。
https://stackoverflow.com/questions/54070691
复制相似问题