python list directory files

Do you want to find out how to display all directory’s files using Python?

You can use os.walk() or glob() in the Python programming language.

To list files and folders you can use os.walk(). From there you can do specific file handling

Did you know Python can download files from the web?

List files and folders

os.walk()

List all the Python files in the directory
and subdirectories:

import os                                                                       
files  = []                                                                     
cwd = os.getcwd()                                                               
# (r)oot, (d)irectory, (f)iles for r,d,f in os.walk(cwd):                                                      
    for file in f:                                                              
        if '.py' in file:                                                       
            files.append(os.path.join(r,file))                                  

for f in files:                                                                 
    print(f)      

List folders and sub folders

You can also use os.walk() to get the folders and sub-folders.

import os
cwd =os.getcwd()
print("folder {}".format(cwd))

folders = []
for r,d,f in os.walk(cwd):
    for folder in d:
            folders.append(os.path.join(r, folder))

for f in folders:
    print(f)

You can run this both in the terminal and the web.

glob.glob()

The function .glob() can be used for the same purpose. To list all files with the py extension

import glob                                                                     
cwd = "/home/you/Desktop/"                                                    
files = [f for f in glob.glob(cwd + "**/*.py", recursive=True)]                 
for f in files:                                                                 
    print(f)    

To list all folders and sub folders

import glob
cwd = "/home/you/Desktop/"
folders = [f for f in glob.glob(cwd + "**/", recursive=True)]
for f in folders:
     print(f)

If you are new to Python, I suggest this Python book and course

原文链接:python list directory files

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容