<div class="toc">
<p class="toc-title">目录
<div class="toc-list">
3.4版本之前使用os.path模块,3.4版本之后建议使用pathlib模块
解释 |
---|
>>> from os import path
>>> p = path.join('/usr','local/httpd/httpd.conf')
>>> p
'/usr/local/httpd/httpd.conf'
>>> type(p)
>>> path.dirname(p)
'/usr/local/httpd'
>>> path.basename(p)
'httpd.conf'
>>> path.split(p)
('/usr/local/httpd','httpd.conf')
p
'/etc/local/http/httpd.conf'
while p != path.dirname(p):
... p = path.dirname(p)
... print(p,path.basename(p))
...
/etc/local/http http
/etc/local local
/etc etc
/
from pathlib import Path
Path中返回的是一个Path对象,而os.path中返回的是一个字符串。
初始化:
>>> p = Path() # 当前目录
p = Path('a','b','c/d') # 当前目录下的a/b/c/d
p = Path('/etc') # 根下的etc目录
解释 |
---|
>>> p = Path('/usr/local/httpd/httpd.conf')
p.name
'httpd.conf'
p.stem
'httpd'
p.suffix
'.conf'
p.with_name('httpd.txt')
PosixPath('/usr/local/httpd/httpd.txt')
解释 |
---|
>>> Path.cwd()
PosixPath('/home/yanfa')
Path.home()
PosixPath('/home/yanfa')
p = Path('/home/yanfa')
p
PosixPath('/home/yanfa')
p.is_dir()
True
p.is_file()
False
p.is_absolute()
True
创建目录:
>>> p = Path()
p /= 'a/b/c/d'
p.exists()
False
p.mkdir() # FileNotFoundError
Traceback (most recent call last):
File "",line 1,in
File "/usr/local/python3.6/lib/python3.6/pathlib.py",line 1248,in mkdir
self._accessor.mkdir(self,mode)
File "/usr/local/python3.6/lib/python3.6/pathlib.py",line 387,in wrapped
return strfunc(str(pathobj),*args)
FileNotFoundError: [Errno 2] No such file or directory: 'a/b/c/d'
p.mkdir(parents=True)
p.exists()
True
通配符匹配:
>>> p = Path()
list(p.glob('h*'))
[PosixPath('h'),PosixPath('hello')]
list(p.glob('**/*.py'))
[PosixPath('pass_py.py')]
g = p.rglob('*.py')
next(g)
PosixPath('pass_py.py')
next(g)
Traceback (most recent call last):
File "",in
StopIteration
p = Path('a/b/c/d')
p = Path('a/b/c/ddd.py')
p.match('d*.py')
True
p.match('c/d*.py')
True
p.match('b/*/d*.py')
True
open(mode='r',buffering=-1,encoding=None,errors=None,newline=None
如何内建的open,返回一个文件对象。>>> from pathlib import Path
p = Path('hello')
p.write_text('hello python')
12
p.read_text()
'hello python'
with p.open() as f:
... print(f.read())
...
hello python