Getting Every File in a Windows Directory
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")]
import fnmatch
import os
return [file for file in os.listdir('.') if fnmatch.fnmatch(file, '*.txt')]
import os
import glob
os.chdir('c:/mydir')
files = glob.glob('*.txt')
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")]