python遍历指定后缀名的文件


方法1:

#! /usr/bin/python
# -*- coding: utf-8 -*-

import os


def getFileName(path):
    ''' 获取指定目录下的所有指定后缀的文件名 '''

    f_list = os.listdir(path)
    # print f_list
    for i in f_list:
        # os.path.splitext():分离文件名与扩展名
        if os.path.splitext(i)[1] == '.log':
            print i


if __name__ == '__main__':

    path = '/home/xx/work/ETS/log/1/1'
    getFileName(path)

方法2:

#!/usr/bin/python
import os

for root , dirs, files in os.walk(r'E:\.m2\repository'):
    for name in files:
        if name.endswith(".repositories") or name.endswith(".sha1"):
            os.remove(os.path.join(root, name))
            print ("Delete File: " + os.path.join(root, name))
os.system("pause")

方法3:

#coding=utf-8
import os

def list_allfile(path,all_files=[],all_py_files=[]):    
    if os.path.exists(path):
        files=os.listdir(path)
    else:
        print('this path not exist')
    for file in files:
        if os.path.isdir(os.path.join(path,file)):
            list_allfile(os.path.join(path,file),all_files)
        else:
            all_files.append(os.path.join(path,file))
    for file in all_files:
        if file.endswith('.py'):
            all_py_files.append(file)
    return all_py_files


    
if __name__ == "__main__":
    print(list_allfile(r'D:\学习资料\kira'))

方法4:

匹配时也可用正则表达式来。

#coding=utf-8
import os
import re

def list_allfile(path,all_files=[],all_py_files=[]):    
    if os.path.exists(path):
        files=os.listdir(path)
    else:
        print('this path not exist')
    for file in files:
        if os.path.isdir(os.path.join(path,file)):
            list_allfile(os.path.join(path,file),all_files)
        else:
            all_files.append(os.path.join(path,file))
    for file in all_files:
        if re.match('.+\.py$',file):
            all_py_files.append(file)
    return all_py_files


    
if __name__ == "__main__":
    print(list_allfile(r'D:\学习资料\kira'))

方法3、4来源:python遍历文件夹找到指定后缀名结尾的文件 - 知乎 (zhihu.com)

方法1来源:(43条消息) python获取指定目录下的所有指定后缀的文件名_zhuxiongxian的博客-CSDN博客_python 搜索后缀文件

方法2来源:(43条消息) python遍历删除指定后缀文件_taoyuanforrest的博客-CSDN博客_python删除指定后缀文件