从 python 中的文件夹中仅提取某些文件作为列表

问题描述 投票:0回答:2

我的文件夹中有以下文件列表:

data.txt
an_123.txt
info.log
an_234.txt
filename.txt
main.py
an_55.txt

我只想提取具有前缀

.txt
作为列表的
an
文件。输出应如下所示:

[an_123.txt,
an_234.txt,
an_55.txt]

到目前为止我尝试了什么?

import glob
mylist = [f for f in glob.glob("*.txt")]

这将打印所有“.txt”文件。如何仅提取带有“an”的文件名?

python list extract filenames glob
2个回答
1
投票

你需要用语言描述你想要的内容

glob.glob
理解,你的代码经过最小的改变可能如下所示:

import glob
mylist = [f for f in glob.glob("an*.txt")]

考虑到

glob.glob
本身返回列表,这可能会简化为

import glob
mylist = glob.glob("an*.txt")

0
投票

对于这种情况,您还可以使用简单的列表理解:

import os

files_list = [f for f in os.listdir() if f[:2] == 'an']

© www.soinside.com 2019 - 2024. All rights reserved.