python的文件和目录访问(一)基础

导入主类:
>>> from pathlib import Path
列出子目录:
>>> p = Path('.')
>>> [x for x in p.iterdir() if x.is_dir()]
[PosixPath('.hg'), PosixPath('docs'), PosixPath('dist'),
PosixPath('__pycache__'), PosixPath('build')]
列出当前目录树下的所有 Python 源代码文件:
>>> list(p.glob('**/*.py'))
[PosixPath('test_pathlib.py'), PosixPath('setup.py'),
PosixPath('pathlib.py'), PosixPath('docs/conf.py'),
PosixPath('build/lib/pathlib.py')]
在目录树中移动(拼接路径):
>>> p = Path('/etc')
>>> q = p / 'init.d' / 'reboot'
>>> q
PosixPath('/etc/init.d/reboot')

拼接路径的另一种方式:class pathlib.PurePath(*pathsegments)

>>> PurePath('foo', 'some/path', 'bar')
PurePosixPath('foo/some/path/bar')
>>> PurePath(Path('foo'), Path('bar'))
PurePosixPath('foo/bar')
返回路径字符串
>>> p = PurePath('/etc')
>>> str(p)
'/etc'
返回路径各部分
>>> p = PurePath('/usr/bin/python3')
>>> p.parts
('/', 'usr', 'bin', 'python3')
访问父路径PurePath.parents
>>> p = PureWindowsPath('c:/foo/bar/setup.py')
>>> p.parents[0]
PureWindowsPath('c:/foo/bar')
>>> p.parents[1]
PureWindowsPath('c:/foo')
>>> p.parents[2]
PureWindowsPath('c:/')
返回逻辑父路径PurePath.parent
>>> p = PurePosixPath('/a/b/c/d')
>>> p.parent
PurePosixPath('/a/b/c')
最后路径组件的字符串,排除了驱动器与根目录:PurePath.name
>>> PurePosixPath('my/library/setup.py').name
'setup.py'
最后一个组件的文件扩展名,如果存在:PurePath.suffix
>>> PurePosixPath('my/library/setup.py').suffix
'.py'
>>> PurePosixPath('my/library.tar.gz').suffix
'.gz'
>>> PurePosixPath('my/library').suffix
''
路径的文件扩展名列表:PurePath.suffixes
>>> PurePosixPath('my/library.tar.gar').suffixes
['.tar', '.gar']
>>> PurePosixPath('my/library.tar.gz').suffixes
['.tar', '.gz']
>>> PurePosixPath('my/library').suffixes
[]
最后一个路径组件,除去后缀:PurePath.stem
>>> PurePosixPath('my/library.tar.gz').stem
'library.tar'
>>> PurePosixPath('my/library.tar').stem
'library'
>>> PurePosixPath('my/library').stem
'library'
返回使用正斜杠(/)的路径字符串:PurePath.as_posix()
>>> p = PureWindowsPath('c:\\windows')
>>> str(p)
'c:\\windows'
>>> p.as_posix()
'c:/windows'
将每个 other 参数中的项目连接在一起:PurePath.joinpath(*other)
>>> PurePosixPath('/etc').joinpath('passwd')
PurePosixPath('/etc/passwd')
>>> PurePosixPath('/etc').joinpath(PurePosixPath('passwd'))
PurePosixPath('/etc/passwd')
>>> PurePosixPath('/etc').joinpath('init.d', 'apache2')
PurePosixPath('/etc/init.d/apache2')
>>> PureWindowsPath('c:').joinpath('/Program Files')
PureWindowsPath('c:/Program Files')
PurePath.match(pattern)

将此路径与提供的通配符风格的模式匹配。如果匹配成功则返回 True,否则返回 False。如果 pattern 是相对的,则路径可以是相对路径或绝对路径,并且匹配是从右侧完成的:

>>> PurePath('a/b.py').match('*.py')
True
>>> PurePath('/a/b/c.py').match('b/*.py')
True
>>> PurePath('/a/b/c.py').match('a/*.py')
False
返回一个新的路径并修改name。如果原本路径没有 name,ValueError 被抛出:PurePath.with_name(name)
>>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
>>> p.with_name('setup.py')
PureWindowsPath('c:/Downloads/setup.py')
返回一个带有修改后stem 的新路径。如果原路径没有名称,则会引发 ValueError:PurePath.with_stem(stem)
>>> p = PureWindowsPath('c:/Downloads/draft.txt')
>>> p.with_stem('final')
PureWindowsPath('c:/Downloads/final.txt')
查询路径的属性:
>>> q.exists()
True
>>> q.is_dir()
False
打开一个文件:
>>> with q.open() as f: f.readline()
...
'#!/bin/bash\n'
>>> p = Path('setup.py')
>>> with p.open() as f:
...
f.readline()
...
'#!/usr/bin/env python3\n'
返回一个新的表示当前目录的路径对象(和os.getcwd() 返回的相同):classmethod Path.cwd()
>>> Path.cwd()
PosixPath('/home/antoine/pathlib')
Path.stat(*, follow_symlinks=True)

返回一个os.stat_result 对象,其中包含有关此路径的信息,例如os.stat()。结果会在每次调用此方法时重新搜索。此方法通常会跟随符号链接;要对 symlink 使用 stat 请添加参数 follow_symlinks=False,或者使用lstat()。

>>> p = Path('setup.py')
>>> p.stat().st_size
956
>>> p.stat().st_mtime
1327883547.852554
此路径是否指向一个已存在的文件或目录:Path.exists()
>>> Path('.').exists()
True
>>> Path('setup.py').exists()
True
解析相对于此路径的通配符 pattern,产生所有匹配的文件,在一个较大的目录树中使用”” 模式可能会消耗非常多的时间Path.glob(pattern)
>>> sorted(Path('.').glob('*.py'))
[PosixPath('pathlib.py'), PosixPath('setup.py'), PosixPath('test_pathlib.py')]
>>> sorted(Path('.').glob('*/*.py'))
[PosixPath('docs/conf.py')]

启用递归通配:

>>> sorted(Path('.').glob('**/*.py'))
[PosixPath('build/lib/pathlib.py'),
PosixPath('docs/conf.py'),
PosixPath('pathlib.py'),
PosixPath('setup.py'),
PosixPath('test_pathlib.py')]
当路径指向一个目录时,产生该路径下的对象的路径:Path.iterdir()

下一层的不返回

>>> p = Path('docs')
>>> for child in p.iterdir(): child    # 在python终端中,试了print(child),可以打印
...
PosixPath('docs/conf.py')
PosixPath('docs/_templates')
PosixPath('docs/make.bat')
PosixPath('docs/index.rst')
PosixPath('docs/_build')
PosixPath('docs/_static')
PosixPath('docs/Makefile')
Path.mkdir(mode=511, parents=False, exist_ok=False)

新建给定路径的目录。如果给出了 mode ,它将与当前进程的 umask 值合并来决定文件模式和访问标志。如果路径已经存在,则抛出FileExistsError。等同与os的mkdir()和makedirs()

以字节对象的形式返回路径指向的文件的二进制内容:Path.read_bytes()
>>> p = Path('my_binary_file')
>>> p.write_bytes(b'Binary file contents')
20
>>> p.read_bytes()
b'Binary file contents'
以字符串形式返回路径指向的文件的解码后文本内容。Path.read_text(encoding=None, errors=None)
>>> p = Path('my_text_file')
>>> p.write_text('Text file contents')
18
>>> p.read_text()
'Text file contents'

文件先被打开然后关闭。有和open() 一样的可选形参。

Path.rename(target)

将文件或目录重命名为给定的 target,并返回一个新的指向 target 的 Path 实例。在 Unix 上,如果target 存在且为一个文件,如果用户有足够权限,则它将被静默地替换。target 可以是一个字符串或者另一个路径对象:

>>> p = Path('foo')
>>> p.open('w').write('some text')
9
>>> target = Path('bar')
>>> p.rename(target)
PosixPath('bar')
>>> target.open().read()
'some text'
Path.replace(target)

将文件名目录重命名为给定的 target,并返回一个新的指向 target 的 Path 实例。如果 target 指向一个现有文件或目录,则它将被无条件地替换。

Path.rmdir()
移除此目录。此目录必须为空的。

Path.touch(mode=438, exist_ok=True)

将给定的路径创建为文件。如果给出了 mode 它将与当前进程的 umask 值合并以确定文件的模式和访问标志。如果文件已经存在,则当 exist_ok 为 true 则函数仍会成功(并且将它的修改事件更新为当前事件),否则抛出FileExistsError。

Path.write_bytes(data)

将文件以二进制模式打开,写入 data 并关闭:

>>> p = Path('my_binary_file')
>>> p.write_bytes(b'Binary file contents')
20
>>> p.read_bytes()
b'Binary file contents'

一个同名的现存文件将被覆盖。

Path.write_text(data, encoding=None, errors=None, newline=None)

将文件以文本模式打开,写入 data 并关闭:

>>> p = Path('my_text_file')
>>> p.write_text('Text file contents')
18
>>> p.read_text()
'Text file contents'

同名的现有文件会被覆盖。可选形参的含义与open() 的相同。

tempfile创建临时文件
>>> import tempfile
# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()
# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...
fp.write(b'Hello world!')
...
fp.seek(0)
...
fp.read()
b'Hello world!'
>>>
# file is now closed and removed
# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...
print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
shutil.rmtree(path, ignore_errors=False, onerror=None)

删除一个完整的目录树;path 必须指向一个目录(但不能是一个目录的符号链接)。如果 ignore_errors
为真值,删除失败导致的错误将被忽略;如果为假值或是省略,此类错误将通过调用由 onerror 所
指定的处理程序来处理,或者如果此参数被省略则将引发一个异常。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值