使用python列出目录下的所有文件

https://stackoverflow.com/questions/3964681/find-all-files-in-a-directory-with-extension-txt-in-python

 

You can use glob:

import glob, os
os.chdir("/mydir")
for file in glob.glob("*.txt"):
    print(file)

or simply os.listdir:

import os
for file in os.listdir("/mydir"):
    if file.endswith(".txt"):
        print(os.path.join("/mydir", file))

or if you want to traverse directory, use os.walk:

import os
for root, dirs, files in os.walk("/mydir"):
    for file in files:
        if file.endswith(".txt"):
             print(os.path.join(root, file))

posted on 2017-08-12 11:41  蚂蚁flow  阅读(319)  评论(0编辑  收藏  举报

导航