Ask Question
27 September, 17:24

Write a recursive function, displayFiles, that expects a pathname as an argument. The path name can be either the name of a file or the name of a directory. If the pathname refers to a file, its filepath is displayed, followed by its contents, like so: File name: file_path Lorem ipsum dolor sit amet, consectetur adipiscing elit ... Otherwise, if the pathname refers to a directory, the function is applied to each name in the directory, like so: Directory name: directory_path File name: file_path1 Lorem ipsum dolor sit amet ... File name: file_path2 Lorem ipsum dolor sit amet ... Test this function in a new program.

+1
Answers (1)
  1. 27 September, 18:40
    0
    The following code will be used to write a recursive function and display files

    Explanation:

    #Import required packages

    import os

    #Define recursive function

    #displayFiles () has a single argument

    #which may be either pathname or filename

    def displayFiles (pathname):

    #if the given argument is pathname for directory

    if (os. path. isdir (pathname)):

    #open the directory

    for item in os. listdir (pathname):

    #append items in the list

    newItem = os. path. join (pathname, item)

    #print each filename

    #call the function recursively

    displayFiles (newItem)

    #otherwise if the pathname

    #is filename

    else:

    #set the pathname to filename

    filename=pathname

    baseFile = os. path. basename (filename)

    print ("File Name: ", baseFile)

    #open the file in read mode

    with open (filename, "r") as file:

    print ("Content:")

    #display the contents of the file

    for line in file:

    #print line

    print (line)

    print ()
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “Write a recursive function, displayFiles, that expects a pathname as an argument. The path name can be either the name of a file or the ...” in 📘 Computers and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers