python 操作简记 (递归查找制定后缀文件)(list排序字典排序 sorted)

《python 操作简记 (递归查找制定后缀文件)(list排序字典排序 sorted)》

递归查找制定后缀的文件

用到三个库

  • glob 是用来匹配文件路径的.比如通过glob.glob('path/*')可返回path路径下的所有文件或文件夹的绝对路径,通过glob.glob('path/*.jpg')返回path路径下的jpg文件绝对路径.
  • os 包含了各种关于路径的函数.在这里我们只用到了os.path.isdir(mPath)判断是不是文件夹.
  • fnmatchfnmatch.fnmatch(mPath, keywords)来匹配后缀是不是符合要求
    实现代码
def recursiveSearchFiles(dirpath, keywords):
    fileList = []
    pathList = glob.glob(os.path.join(dirpath, '*'))
    for mPath in pathList:
        # fnmatch 用于匹配后缀
        if fnmatch.fnmatch(mPath, keywords):
            fileList.append(mPath)  # 符合条件条件加到列表
        elif os.path.isdir(mPath):
            fileList += recursiveSearchFiles(mPath, keywords)  # 将返回的符合文件列表追加到上层
        else:
            pass
    return fileList
if __name__ == '__main__':
    path = recursiveSearchFiles("/home/tianchaoxiong/LinuxData/data/verifies/ceshi/", "*.jpg")
    print(path)

list 转置

排序函数sorted

  1. 数字排序
    list1 = [36, 5, -12, 9, -21]
    list2 = sorted(list1)
    print(list2)

[-21, -12, 5, 9, 36]

  1. 数字按照绝对值排序
    list1 = [36, 5, -12, 9, -21]
    list2 = sorted(list1,key=abs)
    print(list2)

[5, 9, -12, -21, 36]

  1. 数字从大到小
    list1 = [36, 5, -12, 9, -21]
    list2 = sorted(list1, reverse=True)
    print(list2)

[36, 9, 5, -12, -21]

  1. 字符串排序
    list1 = ['bob', 'about', 'Zoo', 'Credit']
    list2 = sorted(list1)
    print(list2)

[‘Credit’, ‘Zoo’, ‘about’, ‘bob’]

  1. 字符串忽略大小写排序
    list1 = ['bob', 'about', 'Zoo', 'Credit']
    list2 = sorted(list1, key=str.lower)
    print(list2)

[‘about’, ‘bob’, ‘Credit’, ‘Zoo’]

  1. 字典排序
    list1 = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
    dict1 = dict(list1)
    # 后面的下表0 表示关键字 1表示value
    dict2 = sorted(dict1.items(), key=lambda d: d[0])  
    print(dict2)

[(‘Adam’, 92), (‘Bart’, 66), (‘Bob’, 75), (‘Lisa’, 88)]

    原文作者:MaxCentaur
    原文地址: https://www.jianshu.com/p/eba41d7e569b
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞