Extract only certain files from a folder in python as list

Question:

I have the following list of files in my folder:

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

I would like to extract only the .txt files that have prefix an as list. The output should look like the following:

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

What I tried so far?

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

This prints all the ‘.txt’ files. How do I extract only the filenames that have ‘an’?

Asked By: MuSu18

||

Answers:

You need to describe what you want in language glob.glob understands, your code after minimal change might look as follows:

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

considering that glob.glob itself returns list this might be simplified to

import glob
mylist = glob.glob("an*.txt")
Answered By: Daweo

You could also use list comprehension:

import os

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

Answered By: Candide
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.