2
import os, glob

file = os.listdir("my directory: example")

mp3files = list(filter(lambda f: f == '*.txt',file))    
print(mp3files)

This code is giving me only : []

smci
  • 32,567
  • 20
  • 113
  • 146
Coldoe
  • 71
  • 1
  • 1
  • 10
  • 3
    Hint: make use of the `glob` module you're importing. :) – NPE May 13 '18 at 11:32
  • Your `lambda f: f == '*.txt'` was literally comparing each filename to see if it matched .txt, hence they all failed and you got empty-list. \* is only a wildcard when some function e.g. regex, string, glob etc. treats it as a wildcard. Otherwise it's a literal * – smci May 13 '18 at 11:40

4 Answers4

1

From Python 3.4 upwards you can use just those two lines for that task:

from pathlib import Path
mp3files = list(Path('.').glob('**/*.txt'))

More info: https://docs.python.org/3/library/pathlib.html

Marqin
  • 1,096
  • 8
  • 17
0
mp3files = list(filter(lambda f: f.endswith('.txt') ,file))

Should work, since the file name do not match (==) to *.txt but rather end with that extension

Ofer Sadan
  • 11,391
  • 5
  • 38
  • 62
0

Use str.endswith:

list(filter(lambda f: f.endswith('.txt'),file))
Netwave
  • 40,134
  • 6
  • 50
  • 93
0

why don't you use the glob module that you have imported ?

mp3files = glob.glob('*.txt')

this will return a list of all mp3 files in your current working directory. if your files are in a different directory and not in your cwd:

path_to_files_dir = os.path.join(os.getcwd(), 'your_files_dir_name', '*.txt')

mp3files = glob.glob(path_to_files)
adnan
  • 1
  • 2