Ask Question
25 November, 21:10

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. 25 November, 21:23
    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?
Get 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 there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers