Tuesday, 21 September 2021

Python: list all the files, folders in a directory

‘os’ module provides listdir function, it return list of all the files, folders in a given directory.

 

Example

files_in_path = os.listdir(path)

 

Find the below working application.

 

list_all_files_in_directory.py

import os

file_to_create = 'testFile.txt'

path = '/Users/Shared/data'
files_in_path = os.listdir(path) 
print("List of directories and files before creating ", file_to_create)
print(files_in_path)

with open(os.path.join(path, file_to_create), 'w') as fp:
    pass;
files_in_path = os.listdir(path) 
print("List of directories and files after creating ", file_to_create)
print(files_in_path)

 

Output

List of directories and files before creating  testFile.txt
['db', 'hello.txt']
List of directories and files after creating  testFile.txt
['db', 'testFile.txt', 'hello.txt']

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment