Search code examples
pythonlistextractfilenamesglob

Extract only certain files from a folder in python as list


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'?


Solution

  • 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")