Search code examples
pythonos.walk

Reading new file with change in folder in python


I am using the import os library to work with all the folders in the current directory. However, I need the program to ask for a file name or path every time it starts to walk through a new folder within the directory. Example: Assuming that There are two folders in a directory namely:

  1. Level Control
  2. Level Change.

when the program walks through Level Control folder, it should read file a.txt. And when walking through Level Change folder, it should read file b.txt. Also assuming that both the files are in the same directory.


Solution

  • By looking at your description, the following code should work (Python 3.x), but some case are not mentioned in your description (e.g. how to handle folders with folder and file), so you may need to do some modifications.

    import os
    
    def walk(root):
        dirs = []
        for item in os.listdir(root):
            if os.path.isdir(os.path.join(root,item)):
                dirs.append(item)
        if len(dirs) > 0:
            for n,d in enumerate(dirs):
                print(f'[{n}] : {d}')
            folder = input('which folder ? ')
            path = os.path.join(root, folder)
            if os.path.isdir(path):
                walk(path)
            print('Invalid path')
        else:
            for file in os.listdir(root):
                print(f'read : {file}')
        
    walk('.')
    

    Instead of os.walk(), you may use os.listdir() as you need to do action according to the content in the current directory.