简体   繁体   中英

How to list all files in a given directory and subdirectories?

I want to take a path from the user and I want to list the file names of all the directories and sub directories in that path. So far, I was only able to get the file names for directories not subdirectories: I'm not allowed to use os.walk()

import sys, os.path

l = []
def fnames(path):
    global l
    l = os.listdir(path)
    print(l)


path = '/Users/sohamphadke/Desktop'

for i in l:
    if os.path.isdir(l) == True:
        fnames(l)
    elif os.path.isdir(l) == False:
        break

glob module is your answer!

You can access the docs here , that say:

If recursive is true, the pattern “ ** ” will match any files and zero or more directories, subdirectories and symbolic links to directories. If the pattern is followed by an os.sep or os.altsep then files will not match

So you could do:

import os
import glob
paths_list = glob.glob('/Users/sohamphadke/Desktop/**/*', recursive=True)

# Separate between files and directories
dirs_list = [path for path in paths_list if os.path.isdir(path)]
files_list = [path for path in paths_list if os.path.isfile(path)]

Hope this helps!

您可以检查os.walk()方法,它会根据您的要求获取您的树。

You can use os.walk to walk through a path. Refer to docs

import os
for root, dirs, files in os.walk(path):
    print("root: {}\ndirs: {}\nfiles: {}".format(root, dirs, files))

If you're allowed to use pathlib ...

path = '/Users/sohamphadke/Desktop'

paths = Path(path).glob("**/*")
file_list = [p for p in paths if p.is_file()]
dir_list = [p for p in paths if p.is_dir()]

Notice paths is a generator, so you may iterate over each path and check if it's a file or a directory at a time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM