python 获取当前文件夹下所有文件名

os 模块下有两个函数:

os.walk()

os.listdir()

 

复制代码
1     # -*- coding: utf-8 -*-   
2       
3     import os  
4       
5     def file_name(file_dir):   
6         for root, dirs, files in os.walk(file_dir):  
7             print(root) #当前目录路径  
8             print(dirs) #当前路径下所有子目录  
9             print(files) #当前路径下所有非目录子文件  
复制代码
复制代码
 1     # -*- coding: utf-8 -*-   
 2       
 3     import os  
 4       
 5     def file_name(file_dir):   
 6         L=[]   
 7         for root, dirs, files in os.walk(file_dir):  
 8             for file in files:  
 9                 if os.path.splitext(file)[1] == '.jpeg':  
10                     L.append(os.path.join(root, file))  
11         return L  
12 
13 
14 #其中os.path.splitext()函数将路径拆分为文件名+扩展名
复制代码
复制代码
 1     # -*- coding: utf-8 -*-  
 2     import os  
 3       
 4     def listdir(path, list_name):  #传入存储的list
 5         for file in os.listdir(path):  
 6             file_path = os.path.join(path, file)  
 7             if os.path.isdir(file_path):  
 8                 listdir(file_path, list_name)  
 9             else:  
10                 list_name.append(file_path)  
复制代码
posted @ 2018-10-09 17:06  核电站  阅读(5864)  评论(0编辑  收藏  举报