Task 4: Functions II#

Remember in a previous lab, you used the tree command to show a map of all directories and files within a directory. In this section, we want to make a similar program, but using python instead.

4.1: ListFiles():#

Task: Your task is to create a python function called ListFiles() that takes in a directory path and then finds and print all the files (not directories) in a given directory (relative to ./).

We suggest you use the listdir() function and isfile() functions from the os module.

In your GitHub repository, there is a folder called directory_list which contains some sample files.

Hint 1: don’t forget to first import os to use os.listdir() and os.path.isfile().

Hint 2: You can see the following tutorials if you need some extra help or some worked examples: link1 and link2.

Sample Output#

directory/file1.txt
directory/file2.txt
directory/file3.txt
directory/file4.txt

#import libraries here
def ListFiles(address):
    # Your Solution here
  Cell In[2], line 2
    # Your Solution here
                        ^
SyntaxError: incomplete input
ListFiles("directory_list")

4.2: ListDirectories():#

Task: Use the os.listdir() and os.path.isdir() function to find and print all the directories (not files) in a given folder. Create a python function ListDirectories(path) that prints all the directories in that folder (and subfolders). You may also use the new pathlib package from Python if you like (highly recommended if you will be programming in the future).

Sample Output (order does not matter)#

directory_list/dir2/
directory_list/dir4/
directory_list/dir3/
directory_list/dir1/

def ListDirectories(address):
    # Your Solution here
ListDirectories("directory_list")

4.3: tree():#

Task: Write a function tree(path) that prints a map of all directories AND files within a directory.

Hint: you can use the functions you created above, or you may use the os.walk() function to complete this task (there are many ways to do it). Another option is to use glob. You can explore multiple solutions if you like.

Sample Output#

directory_list/file1.txt
directory_list/file2.txt
directory_list/file3.txt
directory_list/file4.txt
directory_list/dir1/
directory_list/dir1/file24.txt
directory_list/dir1/file23.txt
directory_list/dir2/
directory_list/dir2/file34.txt
directory_list/dir3/
directory_list/dir3/file110.txt
directory_list/dir3/file140.txt
directory_list/dir3/file130.txt
directory_list/dir3/file120.txt
directory_list/dir4/
directory_list/dir4/file11.txt
directory_list/dir4/file12.txt
directory_list/dir4/file13.txt
directory_list/dir4/file14.txt

def tree(path):
    # Your Solution here
# Test your function
tree("directory_list")