1. 程式人生 > >python每日一類(1):pathlib

python每日一類(1):pathlib

one pre 面向 iss open log python href reg

每天學習一個python的類(大多數都是第三方的),聚沙成金。

--------------------------------------------------------------------------------

今天學習的是:pathlib:(Python3.4+ 標準庫)跨平臺的、面向對象的路徑操作庫.

其官方網址為:https://pathlib.readthedocs.io/en/pep428/

如果只是把path作為string對象來操作,我們會碰到很多很繁瑣的操作,因此,pathlib就是對os.path進行了封裝,提供了一個便捷的,面向對象的操作方式

而且,從python3.4開始,這個類就是標準類庫了

his module offers classes representing filesystem paths with semantics appropriate for different operating systems. Path classes are divided between pure paths, which provide purely computational operations without I/O, and concrete paths, which inherit from pure paths but also provide I/O operations

技術分享

幾個常見的例子:

技術分享
1 from pathlib import *
2 
3 p=Path(.)
4 for x in p.iterdir():
5     if x.is_dir():
6         print(x)
View Code

顯示某個路徑下的py的源文件

 list(p.glob(‘*.py‘))


其源代碼的引入的類如下;
import fnmatch #fnmatch 模塊使用模式來匹配文件名.
import functools 用於高階函數:指那些作用於函數或者返回其它函數的函數,通常只要是可以被當做函數調用的對象就是這個模塊的目標。
import io import ntpath import os import posixpath import re import sys import time from collections import Sequence from contextlib import contextmanager from errno import EINVAL, ENOENT from operator import attrgetter from stat import S_ISDIR, S_ISLNK, S_ISREG, S_ISSOCK, S_ISBLK, S_ISCHR, S_ISFIFO try: from urllib import quote as urlquote, quote as urlquote_from_bytes except ImportError: from urllib.parse import quote as urlquote, quote_from_bytes as urlquote_from_bytes

python每日一類(1):pathlib