python系列13:python中Path常用功能

 

1. 基本功能
建议使用pathlib模块来处理文件和文件夹,可以跨平台。pathlib提供path对象来操作,包括目录和文件。

In [1]: from pathlib import Path

In [2]: p=Path()

In [3]: p
Out[3]: WindowsPath('.')

In [4]: p=Path('a','b','c/d')

In [5]: p
Out[5]: WindowsPath('a/b/c/d')

In [6]: p=Path(r'D:\')
File "<ipython-input-6-5749acb63442>", line 1
p=Path(r'D:\')
^
SyntaxError: EOL while scanning string literal


In [7]: p=Path(r'D:/')

In [8]: p
Out[8]: WindowsPath('D:/')

In [9]: p=Path('/etc')

In [10]: p
Out[10]: WindowsPath('/etc')

 

2. 路径拼接和分解
使用操作符/进行路径拼接,有两种方式:① Path对象/Path对象;② Path对象/字符串,或者字符串/Path对象;也可以使用joinpath方法。

使用Parts属性进行路径分解,可以返回路径中的每一个部分


In [11]: p=Path()

In [12]: p=p/'a'

In [13]: p
Out[13]: WindowsPath('a')

In [14]: p1='b'/p

In [15]: p1
Out[15]: WindowsPath('b/a')

In [16]: p2=Path('c')

In [17]: p2
Out[17]: WindowsPath('c')

In [18]: p3=p2/p1

In [19]: p3
Out[19]: WindowsPath('c/b/a')

In [20]: print(p3.parts)
('c', 'b', 'a')

In [21]: p3.parts
Out[21]: ('c', 'b', 'a')

In [22]: p3.joinpath('etc','int.d',Path('.httpd'))
Out[22]: WindowsPath('c/b/a/etc/int.d/.httpd')

3. 获取路径
Str获取路径字符串。Bytes获取路径字符串的bytes。

In [23]: p=Path('/etc')

 

In [25]: p
Out[25]: WindowsPath('/etc')

In [26]: print(str(p),bytes(p))
\etc b'\\etc'

使用parent获取父目录,使用parents获取所有父目录,使用absolute方法获取绝对路径


In [27]: p=Path('/a/b/c/d')

In [28]: p.parent.parent
Out[28]: WindowsPath('/a/b')

In [29]: p.absolute().parents[len(p.absolute().parents)-1]
Out[29]: WindowsPath('D:/')

 

In [30]: print(len(p.absolute().parents))
4
获取文件路径的方法:
(1)name:目录的最后一个部分
(2)suffix:目录中最后一个部分的拓展名
(3)stem:目录最后一个部分,没有后缀。
(4)suffixes 返回多个扩展名列表。
(5)with_suffix(suffix):补充扩展名到路径尾部,返回新的路径,扩展名存在则无效。
(6)with_name(name):替换目录最后一个部分并返回一个新的路径。

In [31]: p=Path('/etc/config/sys/cf.config.gz')

In [32]: p.name
Out[32]: 'cf.config.gz'

In [33]: p.suffix
Out[33]: '.gz'

In [34]: p.suffixes
Out[34]: ['.config', '.gz']

In [35]: p.with_name('cf.config')
Out[35]: WindowsPath('/etc/config/sys/cf.config')

In [36]: p.with_suffix('.txt')
Out[36]: WindowsPath('/etc/config/sys/cf.config.txt')

4. 文件操作
open(mode=’r’,buffering=-1,encoding=None,errors=None,newline=None):使用方法类似内建函数open,返回一个文件对象。
read_bytes():以’rb’读取路径相对文件,并返回二进制流。
read_text(encoding=None,errors=None):以’rt’ 方式读取路径对应文件,返回文本。
Path.write_bytes(data):以’wb’方式写入数据到路径对应文件。
write_text(data,encoding=None,errors=None):以’wt’方式写入字符串到路径对应文件。


In [37]: p=Path('my_binary_file')

In [38]: p.write_bytes(b'Binary file contents')
Out[38]: 20

In [39]: p.read_bytes()
Out[39]: b'Binary file contents'

In [40]: p=Path('my_text_file')

In [41]: p.write_text('Text file contents')
Out[41]: 18

In [42]: p.read_text()
Out[42]: 'Text file contents'

In [43]: p=Path('test.py')

In [44]: p.write_text('hello python')
Out[44]: 12

In [45]: p.read_text()
Out[45]: 'hello python'

In [46]: with p.open() as f:
...: print(f.read(5))
...:
hello

5. 文件夹操作
(1)as_uri()将文件路径返回URI。
(2)mkdir(mode=0o777,parents=False,exist_ok=False)
(3)Parents,是否创建父目录,True等同于mkdir-p:False时,父目录不存在,则抛出fileNotfounderror。
(4)exist_ok参数,在3.5版本加入,flase时路径存在,抛出异常,True时候异常被忽略。
(5)Iterdir():迭代当前目录
(6)touch(mode=0o666,exist_ok=True)创建一个文件
(7)cwd():返回当前工作目录
(8)home():返回当前目录
(9)is_dir():是否是目录,目录存在返回True.
(10)is_symlink():是否是软连接
(11)is_file():是否是普通文件,文件存在返回True
(12)is_socket():是否是socket文件
(13)is_block_device():是否是块设备。
(14)is_char_device():是否是字符设备
(15)is_absolute():是否是绝对路径
(16)resolve():返回一个新的路径,这个新的路径就是当前Path的绝对路径,如果是软连接则直接被解析
(17)absolute()也可以获取绝对路径,但是推荐使用resolve()
(18)exists()目录或文件是否存在
(19)rmdir()删除空目录,没有提供判断目录为空的方法。
(20)ls():获取所有文件和文件夹


In [47]: p=Path()

In [48]: p.exists()
Out[48]: True

In [49]: p/='a/b/c/d'

In [50]: p.exists()
Out[50]: False

In [51]: p.mkdir()


FileNotFoundError: [WinError 3] 系统找不到指定的路径。: 'a\\b\\c\\d'

In [52]: p.mkdir(parents=True)

In [53]: p
Out[53]: WindowsPath('a/b/c/d')

In [54]: p.exists()
Out[54]: True

In [55]: p.mkdir(parents=True,exist_ok=True)

In [56]: p/='readme.txt'

In [57]: p
Out[57]: WindowsPath('a/b/c/d/readme.txt')

In [58]: p.parent.rmdir()

In [59]: p
Out[59]: WindowsPath('a/b/c/d/readme.txt')

In [60]: p.parent.exists()
Out[60]: False

In [61]: p.mkdir()

FileNotFoundError: [WinError 3] 系统找不到指定的路径。: 'a\\b\\c\\d\\readme.txt'

In [62]: p.mkdir(parents=True)

In [63]: flag=False
...: for _ in x.iterdir():
...: flag=True
...: break
...: print('dir','Not Empty' if flag else 'Empty',sep='\t')
...: elif x.is_file():
...: print('file')
...: else:
...: print('other file')
...:
a aiohttp-spider aiohttp_spider2 lala file
my_binary_file file
my_text_file file
python2 test file
test.py file
test2 file
新建文件夹
6. 通配操作
glob(pattern):通配给定的模式。
rglob(pattern):通配给定的模式,递归目录,返回一个生成器。

In [64]: p.touch()

In [65]: p
Out[65]: WindowsPath('a/b/c/d/readme.txt')

In [66]: p.touch('a')

In [67]: list(p.glob('test*'))
Out[67]: []

In [68]: p
Out[68]: WindowsPath('a/b/c/d/readme.txt')

In [69]: p=Path()

In [70]: p
Out[70]: WindowsPath('.')

In [71]: list(p.glob('test*'))
Out[71]: [WindowsPath('test'), WindowsPath('test.py'), WindowsPath('test2')]

In [72]: list(p.glob('**/*.py'))
Out[72]:
[WindowsPath('test.py'),
WindowsPath('aiohttp-spider/aiohttp_lianjia.py'),
WindowsPath('aiohttp_spider2/aiohttp_spider.py'),

WindowsPath('新建文件夹/python-basic-learning2/PyProject/ds/day17.py'),
WindowsPath('新建文件夹/python-basic-learning2/PyProject/ds/day18.py'),
WindowsPath('新建文件夹/python-basic-learning2/PyProject/ds/__init__.py'),
WindowsPath('新建文件夹/python-fundamentals/hm_01_hello.py'),
WindowsPath('新建文件夹/python-fundamentals/hm_03_注释.py'),
WindowsPath('新建文件夹/python-fundamentals/hm_04_变量.py'),

WindowsPath('新建文件夹/python-fundamentals-/_io/__init__.py')]

In [73]: g=p.rglob('*.py')

In [74]: g
Out[74]: <generator object Path.rglob at 0x000001F730C01A98>

In [75]: next(g)
Out[75]: WindowsPath('test.py')

In [76]: next(g)
Out[76]: WindowsPath('aiohttp-spider/aiohttp_lianjia.py')

In [77]: next(g)
Out[77]: WindowsPath('aiohttp_spider2/aiohttp_spider.py')

In [78]: Path('a/b.py').match('*.py')
Out[78]: True

In [79]: Path('a/b/c.py').match('b/*.py')
Out[79]: True

In [80]: Path('a/b/c.py').match('a/*.py')
Out[80]: False

In [81]: Path('a/b/c.py').match('a/*/*.py')
Out[81]: True

In [82]: Path('a/b/c.py').match('a/**/*.py')
Out[82]: True

In [83]: Path('a/b/c.py').match('**/*.py')
Out[83]: True

In [84]:

posted @ 2022-10-17 01:52  布衣梦蝶1978  阅读(328)  评论(0编辑  收藏  举报