In bash there is ${files_path}/*.txt
that takes all the .txt files in the specific path. Is there an equivalent script in python?
Asked
Active
Viewed 90 times
3 Answers
0
- Import os
- List all files in the directory
- Filter all files that end with "txt"
So something like this:
import os
txt_files = list(filter(lambda x: x.endswith(".txt"), os.listdir(<yourpathhere>)))

Jokab
- 2,939
- 1
- 15
- 26
0
glob
is exactly what you're looking for.
The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell, although results are returned in arbitrary order. No tilde expansion is done, but *, ?, and character ranges expressed with [] will be correctly matched.
Using glob
module:
>>> import os, glob
>>> os.listdir('.')
['package', 'test.py', 'test.pyc', 'test2.py', 'test2.pyc']
>>> glob.glob('*.pyc')
['test.pyc', 'test2.pyc']
>>>

Chen A.
- 10,140
- 3
- 42
- 61
-1
If you use the package os
import os
PATH = "GIVE PATH HERE"
print os.listdir(PATH)

Kenstars
- 662
- 4
- 11