Exercise 58

a) Write a program that lists all the folders in the 'C: / Windows' directory
b) write another program which lists all the files in the 'C: / Windows'  directory.
c) Using the getlogin() method, write a program that make the same operations for the user's Desktop directory.

Solution

a) List of all folder in the directory 'C:/Windows'

# importing the pathlib module 
import os
from pathlib import Path

# creating an empty list which will contain all directories in the chosen directory
folders = []

# choose directory
dir = 'C:/Windows'

# creating a path object from the chosen directory
p = Path(dir)

# looping through the chosen path directory and testing if the entry is directory
for entry in os.scandir(p):
if entry.is_dir():
folders.append(entry)
for rep in folders:
print(rep)

b)List of all file in the directory 'C:/Windows'

# importing the pathlib module  
import os
from pathlib import Path

# creating an empty list which will contain all directories in the chosen directory
fileList = []

# choose directory
dir = 'C:/Windows'

# creating a path object from the chosen directory
p = Path(dir)

# looping through the chosen path directory and testing if the entry is file
for entry in os.scandir(p):
if entry.is_file():
fileList.append(entry)
for file in fileList:
print(file)

c)List of all folder and all file in the desktop directory

# importing the pathlib module 
import os
from pathlib import Path

# creating an empty list which will contain all directories in the chosen directory
fileList = []
directoryList = []

# desktop directory
dir = 'C:/Users/' + os.getlogin() + "/Desktop"

# creating a path object from the chosen directory
p = Path(dir)

# testing if the entry is file or directory
for entry in os.scandir(p):
if entry.is_file():
fileList.append(entry)
else:
directoryList.append(entry)
print("File list in chosen directory :")
for file in fileList:
print(file)
print("Folder list in chosen directory :")
for directory in directoryList:
print(directory)

Younes Derfoufi
my-courses.net

Leave a Reply