In python, rite 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.
Answer.
Step 1 Code:
import os
def readFile(filename):
withopen(filename, "r") as f:
for line in f:
print(line)
def displayFiles(pathname, d=1):
indent = ''
for i inrange(d):
indent = indent + ' '
if (os.path.isdir(pathname)):
for item in os.listdir(pathname):
newItem = os.path.join(pathname, item)
print(indent + newItem)
if (os.path.isdir(newItem)):
displayFiles(newItem,d+1)
else:
print(indent + pathname)
readFile(pathname)
displayFiles("program.txt")
Step 2: Code screenshot for indentation
Thank you.
Get Answers For Free
Most questions answered within 1 hours.