How do I get some list of files in a directory and sub_folders in Python? I want to get only 5 .txt files in each directory.
I've been searched a lot, but can not find answer.
Need your help.
I've been testing Path, glob, os.walk().
import os
for files in Path(".").glob(extension):
print(files)
print all the list of file with extension
import os
cpt = sum([len(files) for r, d, files in os.walk(".")])
cpt = [len(files) for r, d, files in os.walk(dpath)]
print(cpt)
[5, 25, 3, 0, 0, 1, 2, 2, 0, 0, 0, 8, 8, 4, 16, 4, 8]
Now all files, But 5 files in each directory.
Get recursively
first 5 x .txt files
starting from dir_path
import os
for root, dirs, files in os.walk(dir_path):
count = 0
for file in files:
if file.endswith(".txt"):
print(os.path.join(root, file))
count += 1
if count == 5:
break
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.