Wyrden
Wyrden

Reputation: 45

os.listdir get files out of folders too

So if you do os.listdir f.e.

os.listdir("C:/Users/user/Desktop")

it prints out files but folders too f.e.

output: ["text.txt","folder"]

so how can you print out every file in the "folder" too because they arent printet out

Upvotes: 1

Views: 874

Answers (1)

Vishwas Patel
Vishwas Patel

Reputation: 331

Just use os.walk, it will give you much better way to track the file names and path as it traverse folders with any depth. Example ->

import os
folder_path = "C:/Users/user/Desktop"
for path, subdirs, files in os.walk(folder_path):
    print(path) # it will print current path
    print(subdirs) # it will print list of folder in that directory
    print(files) # It will print list of files in that directory

Upvotes: 1

Related Questions