glob模块是Python最简单的模块之一,内容非常少,用它可以查找符合特定规则的文件路径名。查找文件时只会用到三个匹配符:
- * :匹配0个或多个字符
- ? : 匹配单个字符
- [] : 匹配指定范围内的字符, 如[0-9]匹配数字
glob.glob():
参数:需要查找的文件路径,可以是绝对路径,也可以是相对路径。
返回值:指定路径下符合条件的文件名的列表, list类型。
实例:
1 2 3 4 5 6 7 8 9 10 11 | import glob for name in glob.glob('./dir/*'): print(name) print(~~~~~~~~~~~~~~~~~~~~~~~~~~~~~) for name in glob.glob('./dir/file?.txt'): print(name) print(~~~~~~~~~~~~~~~~~~~~~~~~~~~~~) for name in glob.glob('./dir/*[0-9].*'): print(name) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | dir/file.txt dir/file1.txt dir/file2.txt dir/filea.txt dir/fileb.txt dir/subdir ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ dir/file1.txt dir/file2.txt dir/filea.txt dir/fileb.txt ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ dir/file1.txt dir/file2.txt |
glob.iglob():
获取一个可编历对象,使用它可以逐个获取匹配的文件路径名。与glob.glob()的区别是:glob.glob同时获取所有的匹配路径,而glob.iglob一次只获取一个匹配路径。
os.path.split()
路径分割函数,参数PATH指一个文件的绝对路径作为参数:
1 2 3 4 5 6 7 | >>>import os >>>os.path.split(r'./work/python/task/split.py') # 给出的是目录和文件名,则输出路径和文件名 ('./work/python/task','split.py') >>>os.path.split(r'./work/python/task/') # 给出的是一个目录名,则输出路径和为空文件名 ('./work/python/task','') >>>os.path.split(r'./work/python/task') ('./work/python','task') |
以 "PATH" 中最后一个 '/' 作为分隔符,分隔后,将索引为0的视为目录(路径),将索引为1的视为文件名。
os.listdir():
此方法返回一个列表,其中包含指定路径下目录和文件的名称。
1 2 3 4 | import os dirct = './work/python/task/' for i in os.listdir(dirct): print(i) |
1 2 3 4 5 6 | test.py train.py split.py datasets.py datasets results |
os.path.isdir():
判断某一对象(需提供绝对路径)是否为目录。
1 2 3 4 5 6 | import os dirct = './work/python/task/' for i in os.listdir(dirct): fulldirct = os.path.join(dirct, i) # 需要使用os.path.join创建绝对路径 if os.path.isdir(fulldirct): # isdir()的参数需要绝对路径 print(i) |
1 2 | datasets results |
os.path.isfile():
用于判断某一对象(需提供绝对路径)是否为文件。
1 2 3 4 5 6 | import os dirct = './work/python/task/' for i in os.listdir(dirct): fulldirct = os.path.join(dirct, i) # 需要使用os.path.join创建绝对路径 if os.path.isfile(fulldirct): # isdir()的参数需要绝对路径 print(i) |
1 2 3 4 | test.py train.py split.py datasets.py |