Get the App
SLTechnology News&Howtos  ›  Development  › 

How does Python list all the files in the directory

Shulou Source: shulou.com Published: 2022-06-03 17:37:37 09月30日 Update

This article mainly introduces Python how to list all the files in the directory, the article is very detailed, has a certain reference value, interested friends must read it!

os.listdir() will provide everything in the directory, files and directories. If you only want files, you can filter os.path using the method.

from os import listdirfrom os.path import isfile, joinonlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]

You can also use os.walk()which will generate two lists for each directory it accesses.

Split into files and directories. If you want only the top-level catalog, you can break it when it first comes out.

from os import walk f = []for (dirpath, dirnames, filenames) in walk(mypath): f.extend(filenames) break

Or, shorter:

from os import walk filenames = next(walk(mypath), (None, None, []))[2] # [] if no file The above is "Python how to list all files in the directory" All the contents of this article, thank you for reading! Hope to share the content to help everyone, more relevant knowledge, welcome to pay attention to the industry information channel!

Tags: Catalogue document content article two value usage interest boy partner method more knowledge first time industry information information channel top level channel health time Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei Shulou Tech Info Apple Shulou Technology macOS