Ask Question
20 November, 01:49

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.

+5
Answers (1)
  1. 20 November, 02:19
    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 & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers