【获取路径grob()】学习笔记
生活随笔
收集整理的這篇文章主要介紹了
【获取路径grob()】学习笔记
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
最近新接觸了一個獲取路徑的方法—grob()。這個方法可以生成一個迭代器,里面會有文件比較全面的信息。并且使用簡單,可以避免之前繁瑣的提取,拼組路徑的操作。
目錄文件結構
GLOB │ glob_test.py │ └───test|└───littkt_rain│ │ 20201010.h|└───your_name| 520| 666.txtglob的使用
Path('XXX').rglob('*') # 迭代遍歷文件夾下所有文件 Path('XXX').glob('*') # 遍歷文子件夾下的文件其中XXX表示路徑,glob的參數是正則表達式表達的文件類型,*代表任意文件
glob_test.py
# -*- coding: utf-8 -*- from pathlib import PathSCRIPT_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總結
以上是生活随笔為你收集整理的【获取路径grob()】学习笔记的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 用MATLAB快速修改txt文件
- 下一篇: 凡人修仙传之晴天传