Getting Every File in a Windows Directory

Question:

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

Asked By: rectangletangle

||

Answers:

import os
import glob

os.chdir('c:/mydir')
files = glob.glob('*.txt')
Answered By: Hugh Bothwell

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")]
Answered By: Greg Hewgill
import fnmatch
import os

return [file for file in os.listdir('.') if fnmatch.fnmatch(file, '*.txt')]
Answered By: Satyajit

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.

Answered By: Jonathan Sternberg

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

from pathlib import Path

glob_path = Path(r"C:okaywhati_guess")
file_list = [str(pp) for pp in glob_path.glob("**/*.txt")]
Answered By: Seanny123
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.