Getting Every File in a Windows Directory

54,985

Solution 1

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

Solution 2

import os
import glob

os.chdir('c:/mydir')
files = glob.glob('*.txt')

Solution 3

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

Solution 4

import fnmatch
import os

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

Solution 5

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.

Share:
54,985

Related videos on Youtube

rectangletangle
Author by

rectangletangle

Updated on July 09, 2022

Comments

  • rectangletangle
    rectangletangle over 1 year

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

  • kurumi
    kurumi almost 13 years
    isn't return only used in a function?
  • John Machin
    John Machin almost 13 years
    Why os.chdir? Consider glob.glob(r'c:\mydir\*.txt')
  • BasedRebel
    BasedRebel almost 13 years
    @John Machin: absolutely true, that's another way to do it.
  • John Machin
    John Machin almost 13 years
    It's also a way to do it without the unnecessary unasked-for side effect of changing [one of] the current working director[y|ies].
  • smci
    smci almost 6 years
    @JohnMachin: because that's what the question asked for: the list of files (not pathnames)

Related