29

I have a folder in Windows 7 which contains multiple .txt files. How would one get every file in said directory as a list?

Seanny123
  • 8,776
  • 13
  • 68
  • 124
rectangletangle
  • 50,393
  • 94
  • 205
  • 275
  • Do you want the list of **files** (not pathnames), e.g. `a.dat b.dat...` not `C:\DIRNAME\SUBDIR\a.dat ....`? – smci May 22 '18 at 00:01
  • Possible duplicate of [How do I list all files of a directory?](https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory) – smci May 22 '18 at 00:05

5 Answers5

26

You can use os.listdir(".") to list the contents of the current directory ("."):

for name in os.listdir("."):
    if name.endswith(".txt"):
        print(name)

If you want the whole list as a Python list, use a list comprehension:

a = [name for name in os.listdir(".") if name.endswith(".txt")]
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
15

All of the answers here don't address the fact that if you pass glob.glob() a Windows path (for example, C:\okay\what\i_guess\), it does not run as expected. Instead, you need to use pathlib:

from pathlib import Path

glob_path = Path(r"C:\okay\what\i_guess")
file_list = [str(pp) for pp in glob_path.glob("**/*.txt")]
Matt
  • 71
  • 1
  • 1
  • 14
Seanny123
  • 8,776
  • 13
  • 68
  • 124
  • This solution works for windows. But will it also work in linux? Need my code to be portable – Plutonium smuggler Dec 02 '18 at 04:39
  • It will work for Linux. Path is more portable than Glob – Seanny123 Dec 02 '18 at 04:43
  • The last line is simpler and [faster](https://stackoverflow.com/questions/3790848/fastest-way-to-convert-an-iterator-to-a-list/64512225#64512225) to write `file_list = list(glob_path.glob("**/*.txt"))` – wisbucky Oct 06 '22 at 17:37
15
import os
import glob

os.chdir('c:/mydir')
files = glob.glob('*.txt')
Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99
2
import fnmatch
import os

return [file for file in os.listdir('.') if fnmatch.fnmatch(file, '*.txt')]
Satyajit
  • 3,839
  • 1
  • 19
  • 14
1

If you just need the current directory, use os.listdir.

>>> os.listdir('.') # get the files/directories
>>> [os.path.abspath(x) for x in os.listdir('.')] # gets the absolute paths
>>> [x for x in os.listdir('.') if os.path.isfile(x)] # only files
>>> [x for x in os.listdir('.') if x.endswith('.txt')] # files ending in .txt only

You can also use os.walk if you need to recursively get the contents of a directory. Refer to the python documentation for os.walk.

Jonathan Sternberg
  • 6,421
  • 7
  • 39
  • 58