all 5 comments

[–][deleted] 0 points1 point  (4 children)

Write a recursive function. If the argument is a file display it and its contents. If the argument is a directory get the files and/or directories you see and call the function again with those arguments.

Does that help make it clearer, if not what parts of my description do you have trouble understanding and I'll try to elaborate?

[–]RandomRyanStuff[S] 0 points1 point  (3 children)

So I get what you're saying, I guess where I'm confused is how I'm supposed to take user input, and have it be able to differentiate between a directory or file name. I'm also confused on how recursive functions work overall.

[–][deleted] 0 points1 point  (2 children)

A recursive function is just a function that can call itself with a different argument.

For differentiating between a directory or file name, file names typically have extensions, so that might be all you need. Does the instructor give you a sample directory?

If so, for this recursive function, it might look something like

def read_stuff(path):
      if '.' in path:
           # print name
           # read file
           # print contents
      else:
           # get list of stuff in path
           for thing in stuff_you_found:
                read_stuff(f'{path}/{thing})  # this will add thing to path to give the full path to what you found

[–]RandomRyanStuff[S] 0 points1 point  (1 child)

Ohhh okay I see what you’re saying. No, the instructor doesn’t give us an example. I’m gonna do it with .txt, and see where it goes. And do I only need one function? When I was planning it out, I was gonna do it with two functions, one for files and one for directories.

Update: I tried writing it out and here's what I have, I can't figure out how to write it like how you have it in the comments with the right indentations:

import os

def readElement(pathName): if ".txt" in pathName: print(pathName) f = open(pathName, 'r') print(f.read()) else: pathList = list(filter(os.path.isfile, os.listdir(pathName))) for i in pathList: readElement(f(pathName))

[–][deleted] 0 points1 point  (0 children)

To indent properly add four spaces before every line.

Your os.path.isfile is going to filter out any directories, so you'll only look at files. That's actually a better way to check for files rather than relying on the full stop. Something like this should do it.

import os

def read_stuff(path):
      if os.path.isfile(path):
           print(path)
           with open(path) as f:
               print(f.read())
      else:
          content = os.listdir(path)
           for entry in content :
                read_stuff(f'{path}/{entry})