Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does Python list all the files in the directory

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

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!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report