A-A+

python 2.x _3.x 获取目录下所有文件 _ 获取目录列表

2018年12月18日 18:24 汪洋大海 暂无评论 共2396字 (阅读2,170 views次)

这里先说一下 python 2.x 的获取方法:
python os模块、glob模块列出文件夹下所有文件。

python模块:
python os模块
python sys模块
python glob模块
python math模块
python re模块

例子:

1
2
3
4
#方法1:使用os.listdir
import os
for filename in os.listdir(r'c:\windows'):
    print filename
1
2
3
4
#方法2:使用glob模块,可以设置文件过滤
import glob
for filename in glob.glob(r'c:\windows\*.exe'):
    print filename
1
2
3
4
5
6
7
import os.path
def processDirectory ( args, dirname, filenames ):
    print 'Directory',dirname
    for filename in filenames:
        print ' File',filename
 
os.path.walk(r'c:\windows', processDirectory, None )

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

1
2
3
4
5
6
7
8
9
#方法4:非递归
#!/bin/python
#
#site:www.jbxue.com
import os
for dirpath, dirnames, filenames in os.walk('c:\\winnt'):
    print 'Directory', dirpath
    for filename in filenames:
        print ' File', filename

另外,判断文件与目录是否存在:

1
2
3
import os
os.path.isfile('test.txt') #如果不存在就返回False
os.path.exists(directory) #如果目录不存在就返回False

因为python 3.x 与2不同,所以下面是 python3.x 的获取方法
os 模块下有两个函数:
os.walk()
os.listdir()

1
2
3
4
5
6
7
8
9
10
#方法一:
# -*- coding: utf-8 -*-   
 
import os  
 
def file_name(file_dir):   
        for root, dirs, files in os.walk(file_dir):  
            print(root) #当前目录路径  
            print(dirs) #当前路径下所有子目录  
            print(files) #当前路径下所有非目录子文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 #方法二:
# -*- coding: utf-8 -*-   
 
    import os  
 
    def file_name(file_dir):   
        L=[]   
        for root, dirs, files in os.walk(file_dir):  
            for file in files:  
                if os.path.splitext(file)[1] == '.jpeg':  
                    L.append(os.path.join(root, file))  
        return L  
 
 
#其中os.path.splitext()函数将路径拆分为文件名+扩展名
1
2
3
4
5
6
7
8
9
10
11
#方法三:
# -*- coding: utf-8 -*-  
    import os  
 
    def listdir(path, list_name):  #传入存储的list
        for file in os.listdir(path):  
            file_path = os.path.join(path, file)  
            if os.path.isdir(file_path):  
                listdir(file_path, list_name)  
            else:  
                list_name.append(file_path)

PHP 在很多场景应用太麻烦,没办法只能硬着头皮学python ,记录一下。

这里还有一个获取所有的脚本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/usr/bin/python  
# -*- coding:utf8 -*-  
 
import os  
allFileNum = 0  
def printPath(level, path):  
    global allFileNum  
    ''''' 
    打印一个目录下的所有文件夹和文件 
    '''  
    # 所有文件夹,第一个字段是次目录的级别  
    dirList = []  
    # 所有文件  
    fileList = []  
    # 返回一个列表,其中包含在目录条目的名称(google翻译)  
    files = os.listdir(path)  
    # 先添加目录级别  
    dirList.append(str(level))  
    for f in files:  
        if(os.path.isdir(path + '/' + f)):  
            # 排除隐藏文件夹。因为隐藏文件夹过多  
            if(f[0] == '.'):  
                pass  
            else:  
                # 添加非隐藏文件夹  
                dirList.append(f)  
        if(os.path.isfile(path + '/' + f)):  
            # 添加文件  
            fileList.append(f)  
    # 当一个标志使用,文件夹列表第一个级别不打印  
    i_dl = 0  
    for dl in dirList:  
        if(i_dl == 0):  
            i_dl = i_dl + 1  
        else:  
            # 打印至控制台,不是第一个的目录  
            print '-' * (int(dirList[0])), dl  
            # 打印目录下的所有文件夹和文件,目录级别+1  
            printPath((int(dirList[0]) + 1), path + '/' + dl)  
    for fl in fileList:  
        # 打印文件  
        print '-' * (int(dirList[0])), fl  
        # 随便计算一下有多少个文件  
        allFileNum = allFileNum + 1  
 
if __name__ == '__main__':  
    printPath(1, '/home/lizheng')  
    print '总文件数 =', allFileNum

文章来源:
https://blog.csdn.net/poem_of_sunshine/article/details/51673320
https://www.cnblogs.com/strongYaYa/p/7200357.html
https://www.cnblogs.com/flyhigh1860/p/3896111.html

布施恩德可便相知重

微信扫一扫打赏

支付宝扫一扫打赏

×
标签:

给我留言