python 获取文件夹所有文件列表_python获取文件夹下所有文件及os模块方法

python获取文件夹下所有文件

方法一:使用os.listdir

import os

for filename in os.listdir(r'c:\windows'):

print filename

方法二:使用glob模块,可以设置文件过滤

import glob

for filename in glob.glob(r'c:\windows\*.exe'):

print(filename)

方法三:通过os.path.walk递归遍历,可以访问子文件夹

import os

current_address = os.path.dirname(os.path.abspath(__file__))

for parent, dirnames, filenames in os.walk(current_address):

# Case1: traversal the directories

for dirname in dirnames:

print("Parent folder:", parent)

print("Dirname:", dirname)

# Case2: traversal the files

for filename in filenames:

print("Parent folder:", parent)

print("Filename:", filename)

方法四:非递归

import os

current_address = os.path.dirname(os.path.

你可能感兴趣的:(python,获取文件夹所有文件列表)