最近新接触了一个获取路径的方法—grob()。这个方法可以生成一个迭代器,里面会有文件比较全面的信息。并且使用简单,可以避免之前繁琐的提取,拼组路径的操作。
目录文件结构
GLOB
│ glob_test.py
│
└───test
|
└───littkt_rain
│ │ 20201010.h
|
└───your_name
| 520
| 666.txt
glob的使用
Path('XXX').rglob('*') # 迭代遍历文件夹下所有文件
Path('XXX').glob('*') # 遍历文子件夹下的文件
其中XXX表示路径,glob的参数是正则表达式表达的文件类型,*代表任意文件
glob_test.py
# -*- coding: utf-8 -*-
from pathlib import Path
SCRIPT_DIR = Path(__file__).parent # 获取当前路径
print(SCRIPT_DIR, '\r\n')
for file in Path('test').rglob('*'): # 迭代遍历文件夹下所有文件
print((file, file.parent, file.name, file.suffix))
print('')
for file in Path('test').rglob('*.txt'): # 获取.txt文件
print('FILE:', file, '\r\n')
for file in Path('test').glob('*'): # 遍历文子件夹下的文件
print('FILE:', file)
运行结果
C:\Users\86153\Desktop\GLOB
(WindowsPath('test/little_rain'), WindowsPath('test'), 'little_rain', '')
(WindowsPath('test/your_name'), WindowsPath('test'), 'your_name', '')
(WindowsPath('test/little_rain/20201010.h'), WindowsPath('test/little_rain'), '20201010.h', '.h')
(WindowsPath('test/your_name/520'), WindowsPath('test/your_name'), '520', '')
(WindowsPath('test/your_name/666.txt'), WindowsPath('test/your_name'), '666.txt', '.txt')
FILE: test\your_name\666.txt
FILE: test\little_rain
FILE: test\your_name