Search code examples
pythonlinuxoperating-systemos.walktilde

Python os.walk() does not work with tilde ~ in path


I am trying to count files in a directory and subdirectories and it will be used for many users which I dont know before hand so I want to use "~" tilde in the path. But when I do the following python returns nothing:

import os 

for root, dirs, files in os.walk("~/direcotry/sub_directory", topdown=True):
    for name in dirs:
        print(os.path.join(root, name))

    total += len(files)

print(f"Total number of files in directory is:{total}")

Solution

  • Using the reply above the code works like this now:

    import os 
    
    exapnded_dir = os.path.expanduser('~/direcotry/sub_directory')
    for root, dirs, files in os.walk(exapnded_dir, topdown=True):
        for name in dirs:
            print(os.path.join(root, name))
    
        total += len(files)
    
    print(f"Total number of files in directory is:{total}")