1import os
2
3files = os.listdir('.')
4print(files)
5for file in files:
6 # do something
7
1>>> [ name for name in os.listdir(thedir) if os.path.isdir(os.path.join(thedir, name)) ]
2['ctypes', 'distutils', 'encodings', 'lib-tk', 'config', 'idlelib', 'xml', 'bsddb', 'hotshot', 'logging', 'doc', 'test', 'compiler', 'curses', 'site-packages', 'email', 'sqlite3', 'lib-dynload', 'wsgiref', 'plat-linux2', 'plat-mac']
1import os
2
3def get_filepaths(directory):
4 """
5 This function will generate the file names in a directory
6 tree by walking the tree either top-down or bottom-up. For each
7 directory in the tree rooted at directory top (including top itself),
8 it yields a 3-tuple (dirpath, dirnames, filenames).
9 """
10 file_paths = [] # List which will store all of the full filepaths.
11
12 # Walk the tree.
13 for root, directories, files in os.walk(directory):
14 for filename in files:
15 # Join the two strings in order to form the full filepath.
16 filepath = os.path.join(root, filename)
17 file_paths.append(filepath) # Add it to the list.
18
19 return file_paths # Self-explanatory.
20
21# Run the above function and store its results in a variable.
22full_file_paths = get_filepaths("/Users/johnny/Desktop/TEST")
1Python By Charming Caribou on Mar 26 2020
2import os
3
4def get_filepaths(directory):
5 """
6 This function will generate the file names in a directory
7 tree by walking the tree either top-down or bottom-up. For each
8 directory in the tree rooted at directory top (including top itself),
9 it yields a 3-tuple (dirpath, dirnames, filenames).
10 """
11 file_paths = [] # List which will store all of the full filepaths.
12
13 # Walk the tree.
14 for root, directories, files in os.walk(directory):
15 for filename in files:
16 # Join the two strings in order to form the full filepath.
17 filepath = os.path.join(root, filename)
18 file_paths.append(filepath) # Add it to the list.
19
20 return file_paths # Self-explanatory.
21
22# Run the above function and store its results in a variable.
23full_file_paths = get_filepaths("/Users/johnny/Desktop/TEST")
1from os import listdir
2
3## Prints the current directory as a list (including file types)
4print(os.listdir())
5