0%

找文件用的Python代码片段

摘要

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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# coding=utf-8
# python=2.7

import os as os
import re as re

# NOTE: 仅用于类型注释
try:
import typing as typing
except:
pass

class FilePathProcessor(object):
u"""用于处理文件的类"""

@classmethod
def CheckIfDirExist (cls, dirPath):
# type: (str)->None
u"""判断文件夹是否存在, 否则抛出异常"""

if not os.path.exists(dirPath):
raise Exception(u"不存在文件夹, 或不是文件夹 : {}".format(dirPath))

@classmethod
def GetAllFileWithExt (cls, dirPath, extFormat, bSingleDir=True):
# type: (str, str, bool) -> typing.Iterable[str]
u"""遍历文件夹以寻找特定格式的文件"""

# NOTE: 判断文件夹是否存在, 否则抛出异常
cls.CheckIfDirExist (dirPath)

# NOTE: 小写后缀扩展格式
lowerExtFormat = extFormat.lower()

# NOTE: 返回一个 路径生成器
if bSingleDir: # NOTE 单层模式
for fileName in os.listdir(dirPath):
tempFilePath = os.path.join(dirPath,fileName)
# NOTE: 非目录 && 以extFormat结尾
if (not os.path.isdir(tempFilePath)) and (fileName.lower().endswith(lowerExtFormat)):
yield tempFilePath
else : # NOTE 遍历所有子目录
for dirPath,dirNames,fileNames in os.walk(dirPath):
for fileName in fileNames:
# NOTE: 以extFormat结尾
if fileName.lower().endswith(lowerExtFormat):
yield os.path.join(dirPath, fileName)

@classmethod
def GetAllFileRegexWithExt (cls, dirPath, extFormat, bSingleDir=True, bUseRegex=False, regexRule=""):
# type: (str, str, bool, bool, str) -> typing.Iterable[str]
u"""遍历文件夹以寻找特定格式的文件, 且可选是否包含特定的Regex"""

pathGenerator = cls.GetAllFileWithExt(dirPath,extFormat,bSingleDir)
if not bUseRegex: # NOTE 不使用正则表达式
for filePath in pathGenerator:
yield filePath
else : # NOTE 使用正则表达式
regexMatchRule = re.compile(regexRule,re.I)
for filePath in pathGenerator:
regexMatched = regexMatchRule.search(os.path.basename(filePath))
if regexMatched != None :
yield filePath


# NOTE: Easy CV!
if __name__ == "__main__":
targetDirPath = os.environ["userprofile"]
targetExtFormat = ".fbx"
bUseSingleDir = False
bUseRegex = True
regexRule = r"^anim.*?"
filePathGenerator = FilePathProcessor.GetAllFileRegexWithExt(
targetDirPath,
targetExtFormat,
bUseSingleDir,
bUseRegex,
regexRule)

for filePath in filePathGenerator :
print(filePath)

歡迎關注我的其它發布渠道