Python基础学习:pathlib模块

pathlib——面向对象的文件系统路径

代码资源:Lib/pathlib.py

该模块提供了一些使用语义表达来表示文件系统路径的类,这些类适合多种操作系统。路径类被划分为纯路径(该路径提供了不带I/O的纯粹计算操作),以及具体路径(从纯路径中继承而来,但提供了I/O操作)。

如果你之前从未使用过该模块或者不能确认该模块中那个类是你的任务所需要,请使用Path函数进行判别。它实例化了一个平台代码运行的具体路径。

纯路径被使用在一些特殊的情况里,如:

1. 如果你需要在Unix设备里操作Windows路径,或在Windiws设备里操作Unix路径。你不能实例化一个Windows路径当其在Unix上运行,但是你可以实例化一个纯Windows路径。

2. 你想要确保你的代码值操作路径而不通过操作系统。在这种情况中,一个纯类的实例就可以被用到,因为它完全不包含操作系统访问操作。

针对在字符串上的低级路径操作,你也可以使用os. path模块。

1. 基本使用

导入主类:

>>> frompathlibimport 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')

>>> q.resolve()

PosixPath('/etc/rc.d/init.d/halt')

查询路径属性:

>>> q.exists()

True

>>> q.is_dir()

False

打开文件:

>>> with q.open() as f: f.readline()

...

'#!/bin/bash\n

2.纯路径

纯路径对象提供路径处理操作,该操作实际上不使用文件系统。这里有三种方法使用这些类,这也是该语言的特色:

class pathlib. PurePath(*pathsegments)

一个用来表示系统路径特色的通用类(实例化它创建一个PurePosixPath纯Poxix路径或一个PureWindowosPath纯Windowos路径):

>>>PurePath('setup.py')      # Running on a Unix machine

PurePosixPath('setup.py')

pathsegments中的每个元素都可以是一个辨识路径片段的字符串、一个可以返回字符串的实现了os.PathLike接口的对象、或是其它的路径对象:

>>>PurePath('foo', 'some/path', 'bar')

PurePosixPath('foo/some/path/bar')

>>>PurePath(Path('foo'), Path('bar'))

PurePosixPath('foo/bar')

当pathsegments为空,当前的目录就会被判定为:

>>>PurePath()

PurePosixPath('.')

当一系列绝对地址被给出,最新给出的路径将被当做锚使用(模仿os. path. join()的行为):

>>>PurePath('/etc', '/usr', 'lib64')

PurePosixPath('/usr/lib64')

>>>PureWindowsPath('c:/Windows', 'd:bar')

PureWindowsPath('d:bar')

然而,在Windows路径中,改变本地根不会丢失先前的驱动设置:

>>>PureWindowsPath('c:/Windows', '/Program Files')

PureWindowsPath('c:/ProgramFiles')

假斜杠和单个点会被折叠,但是两个点却不会,这是因为这会改变路径在符号链路层级上的意义:

>>>PurePath('foo//bar')

PurePosixPath('foo/bar')

>>>PurePath('foo/./bar')

PurePosixPath('foo/bar')

>>>PurePath('foo/../bar')

PurePosixPath('foo/../bar')

(一种天真的实施认为PurePosix(‘foo/../bar’)等价于PurePosixPath(‘bar’),但是这是不对的,因为foo可能是一个连接到其它目录里的符号。)

纯路径独享使用os. PathLike接口,允许他们可以在接口允许的环境下随意使用。

class  pathlib. PurePosixPath(*pathsegments)

PurePath的一个子类,这个路径特点为表示非Windowos问价系统路径:

>>>PurePosixPath('/etc')

PurePosixPath('/etc')

pathsegments与PurePath中的类似。

class pathlib. PureWindowsPath(*pathsegments)

PurePath的子类,该路径的特点是表示Windowos文件系统路径:

>>>PureWindowsPath('c:/Program Files/')

PureWindowsPath('c:/ProgramFiles')

2.1 通用属性

路径是不可变的量,它具有布尔属性。具有相同格式的路径是可比可排序的。这些属性支持语义时间折叠的特点:

>>>PurePosixPath('foo') == PurePosixPath('FOO')

False

>>>PureWindowsPath('foo') == PureWindowsPath('FOO')

True

>>>PureWindowsPath('FOO') in { PureWindowsPath('foo') }

True

>>>PureWindowsPath('C:') < PureWindowsPath('d:')

True

不同格式的路径比较时不相等且不可被排序。

>>>PureWindowsPath('foo') == PurePosixPath('foo')

False

>>>PureWindowsPath('foo') < PurePosixPath('foo')

Traceback(most recent call last):

  File "<stdin>", line 1, in<module>

TypeError: '<' not supported between instances of'PureWindowsPath' and 'PurePosixPath'

2.2 操作符

斜杠操作符可以帮助创建子路径,类似于os. path. join():

>>>p = PurePath('/etc')

>>>p

PurePosixPath('/etc')

>>>p /'init.d'/'apache2'

PurePosixPath('/etc/init.d/apache2')

>>>q = PurePath('bin')

>>>'/usr'/ q

PurePosixPath('/usr/bin')

路径对象可以在任何支持os. PathLike的地方被使用:

>>>importos

>>>p = PurePath('/etc')

>>>os.fspath(p)

'/etc'

字符串表示路径时,其本身为未处理的文件系统路径(处于原始格式,即在Windowos下存在反斜杠),你可以把文件路径以字符串的格式传递给任何函数:

>>>p = PurePath('/etc')

>>>str(p)

'/etc'

>>>p = PureWindowsPath('c:/Program Files')

>>>str(p)

'c:\\ProgramFiles'

同样的,在一个路径中调用bytes,将把未处理的文件系统路径转化为字节对象,编码形式类似于os. fsencode():

>>>bytes(p)

b'/etc'

注意:调用bytes最好只在Unix环境下进行。在Windowos环境下,统一码格式是文件系统路径的正则表达。

2.3 调用独立部分

为了调用路径的独立“部分”(组件),使用以下属性:

PurePath. parts

给出一个元组访问路径的各种组件:

>>>p = PurePath('/usr/bin/python3')

>>>p.parts

('/','usr', 'bin', 'python3')

 

>>>p = PureWindowsPath('c:/Program Files/PSF')

>>>p.parts

('c:\\','Program Files', 'PSF')

(注意:驱动和本地根是如何在单个部件中重新组合的)

2.4 方法和属性

纯路径提供了以下方法和属性:

PurePath. drive其

    如果存在,其为表示驱动编号或名称的字符串:

>>>PureWindowsPath('c:/Program Files/').drive

'c:'

>>>PureWindowsPath('/Program Files/').drive

''

>>>PurePosixPath('/etc').drive

''

UNC共享也被认为是驱动:

>>>PureWindowsPath('//host/share/foo.txt').drive

'\\\\host\\share'

PurePath. root

其如果存在,该字符串表示本地或总体根:

>>>PureWindowsPath('c:/Program Files/').root

'\\'

>>>PureWindowsPath('c:Program Files/').root

''

>>>PurePosixPath('/etc').root

'/'

UNC共享总是有根:

>>>PureWindowsPath('//host/share').root

'\\'

PurePath. anchor

驱动和根的级联:

>>>PureWindowsPath('c:/Program Files/').anchor

'c:\\'

>>>PureWindowsPath('c:Program Files/').anchor

'c:'

>>>PurePosixPath('/etc').anchor

'/'

>>>PureWindowsPath('//host/share').anchor

'\\\\host\\share\\

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')

你不能对锚或空路径使用:

>>>p = PurePosixPath('/')

>>>p.parent

PurePosixPath('/')

>>>p = PurePosixPath('.')

>>>p.parent

PurePosixPath('.')

注意:这是一个纯粹的词汇操作,因此由接下来的行为:

>>>p = PurePosixPath('foo/..')

>>>p.parent

PurePosixPath('foo')

如果你想要上移任意文件系统路径,推荐先使用Path. resolve()解决链接和消除“..”组件。

PurePath. name

如果其存在,该字符串表示最终路径组件,除了驱动和根:

>>>PurePosixPath('my/library/setup.py').name

'setup.py

UNC驱动名将被忽略:

>>>PureWindowsPath('//some/share/setup.py').name

'setup.py'

>>>PureWindowsPath('//some/share').name

''

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'

 

PurePath. is_absolute

返回布尔值以回应该路径是否为绝对路径。如果一个路径中包含根和允许的驱动,那它有可能是绝对路径。

>>>PurePosixPath('/a/b').is_absolute()

True

>>>PurePosixPath('a/b').is_absolute()

False

 

>>>PureWindowsPath('c:/a/b').is_absolute()

True

>>>PureWindowsPath('/a/b').is_absolute()

False

>>>PureWindowsPath('c:').is_absolute()

False

>>>PureWindowsPath('//some/share').is_absolute()

True

PurePath. is_reserved()

PureWindowsPath格式下,当路径为Windows保留路径时返回True,否则返回False。在PurePosixPath格式下总是返回False。

>>>PureWindowsPath('nul').is_reserved()

True

>>>PurePosixPath('nul').is_reserved()

False

保留路径上文件被系统调用时可能会出现各种各样的意外。

PurePath. joinpath(*other)

调用该方法等价于将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:/ProgramFiles')

PurePath. match(pattern)

将路径与提供的小段路径格式进行匹配。如果匹配成功,返回True;否则,返回False。

如果格式属于相对量,那么用于匹配的路径可以是绝对路径也可以是相对路径,匹配从最右端开始。

>>>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

如果格式是绝对量,路径也必须是绝对路径,匹配将着眼于整体:

>>>PurePath('/a.py').match('/*.py')

True

>>>PurePath('a/b.py').match('/*.py')

False

类似于其他方法,它将捕获敏感事件:

>>>PureWindowsPath('b.py').match('*.PY')

True

PurePath. relative_to(*other)

计算出该路径以other所表示路径构造的相对路径。如果无法计算出,将会抛出ValueError:

>>>p = PurePosixPath('/etc/passwd')

>>>p.relative_to('/')

PurePosixPath('etc/passwd')

>>>p.relative_to('/etc')

PurePosixPath('passwd')

>>>p.relative_to('/usr')

Traceback(most recent call last):

  File "<stdin>", line 1, in<module>

  File "pathlib.py", line 694, in relative_to

    .format(str(self), str(formatted)))

ValueError: '/etc/passwd' does not start with '/usr'

PurePath. with_name(name)

返回一个新的路径,其name属性发生改变。如果原始路径不含有name,将会抛出ValueError:

>>>p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')

>>>p.with_name('setup.py')

PureWindowsPath('c:/Downloads/setup.py')

>>>p = PureWindowsPath('c:/')

>>>p.with_name('setup.py')

Traceback(most recent call last):

  File "<stdin>", line 1, in<module>

  File "/home/antoine/cpython/default/Lib/pathlib.py", line 751, in with_name

    raiseValueError("%r has an emptyname"% (self,))

ValueError: PureWindowsPath('c:/') has an empty name

PurePath. with_suffix(suffix)

返回一个新的路径,但其后缀名发生改变。如果原路径不存在后缀,那么新的后缀将被直接添加:

>>>p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')

>>>p.with_suffix('.bz2')

PureWindowsPath('c:/Downloads/pathlib.tar.bz2')

>>>p = PureWindowsPath('README')

>>>p.with_suffix('.txt')

PureWindowsPath('README.txt')

3. 具体路径

具体路径是纯路径类的一个子类。除了后者提供的操作以外,它们也提供了方法实现对路径对象的系统调用。这里有三种方法实例化具体路径:

class  pathlib. Path(*pathsegments)

PurePath的子类,该类使用系统的特色(实例化它创建PosixPath或WindowsPath)表示具体路径。

>>>Path('setup.py')

PosixPath('setup.py')

pathsegments与PurePath中的类似。

class  pathlib. PosixPath(*pathsegments)

Path和PurePosixPath的子类,该类表示非Windows文件系统路径。

>>>PosixPath('/etc')

PosixPath('/etc')

pathsegments与PurePath中的类似。

class pathlib. WindowsPath(*pathsegments)

Path和PureWindowsPath的子类,该类表示具体的Windows文件系统路径:

>>>WindowsPath('c:/Program Files/')

WindowsPath('c:/ProgramFiles')

你也可以只实例化与自己系统相关的类特色(允许对不兼容的路径特色进行系统调用可能会导致应用程序中的错误或失败):

>>>importos

>>>os.name

'posix'

>>>Path('setup.py')

PosixPath('setup.py')

>>>PosixPath('setup.py')

PosixPath('setup.py')

>>>WindowsPath('setup.py')

Traceback (mostrecent call last):

  File "<stdin>", line 1, in<module>

  File "pathlib.py", line 798, in __new__

    % (cls.__name__,))

NotImplementedError: cannot instantiate 'WindowsPath' on your system

3.1 方法

具体路径相对于纯路径额外提供了以下方法。这些方法中的许多都会在系统调用错误时抛出OSError(例如:路径不存在):

classmethod  Path. cwd()

    返回一个新的路径对象,该对象不是当前的目录(和os. getcwd()的返回值相同):

>>>Path.cwd()

PosixPath('/home/antoine/pathlib')

classmethod  Path. home()

    返回一个新的路径对象表示用户的主页目录(与os. path. expanduser带有~结构时的返回相同):

>>>Path.home()

PosixPath('/home/antoine')

Path. stat()

    返回关于这个路径的信息(类似于os. stat())。该结果查询该方法的所有调用。

>>>p = Path('setup.py')

>>>p.stat().st_size

956

>>>p.stat().st_mtime

1327883547.852554

Path. chmod(mode)

    改变文件模式和允许,类似于os. chmod():

>>>p = Path('setup.py')

>>>p.stat().st_mode

33277

>>>p.chmod(0o444)

>>>p.stat().st_mode

33060

Path. exists()

    确定路径是否指向一个存在的文件或目录:

>>>Path('.').exists()

True

>>>Path('setup.py').exists()

True

>>>Path('/etc').exists()

True

>>>Path('nonexistentfile').exists()

False

注意:如果路径指向一个系统链接,exists()就会测试该系统链接是否指向一个存在的文件或目录。

Path. expanduser()

    返回一个新的路径,该路径带有额外的~和~user结构,其返回值如同os. path. expanduser():

>>>p = PosixPath('~/films/MontyPython')

>>>p.expanduser()

PosixPath('/home/eric/films/MontyPython'

Path. glob(pattern)

    找出在这个路径下包含或与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. group()

    返回拥有该文件的组的名称。如果该文件的gid在系统数据库中无法找出,将会抛出KeyError。

Path. is_dir()

    如果路径指向一个目录(或者是符号链接指向一个目录),返回True;如果指向了其它类型的文件,返回False。

    如果该路径不存在或者是已破损的链接,返回False。传播其他错误(例如权限错误)。

Path. is_file()

    如果该路径指向常规文件(或者符号链接指向常规文件),返回True;如果指向其它类型的文件,返回False。

    如果该路径不存在或者是已破损的链接,返回False。传播其他错误(例如权限错误)。

Path. is_symlink()

    如果该路径指向一个符号链接,返回True。佛则,返回False。

    如果该路径不存在或者是已破损的链接,返回False。传播其他错误(例如权限错误)。

Path. is_socket()

    如果路径指向Unix堆(或者是符号链接指向),返回True;如果指向其它类型的文件,返回False。

    如果该路径不存在或者是已破损的链接,返回False。传播其他错误(例如权限错误)。

Path.is_fifo()

    如果该路径或符号链接指向FIFO,返回True;如果其指向其他类型的文件,返回False。

    如果该路径不存在或者是已破损的链接,返回False。传播其他错误(例如权限错误)。

Path. is_block_decice()

    如果路径指向块设备(或指向块设备的符号链接),则返回True,如果指向另一种文件,则为False。

    如果该路径不存在或者是已破损的链接,返回False。传播其他错误(例如权限错误)。

Path. is_char_device()

    如果路径指向字符设备(或指向字符设备的符号链接),则返回True,如果指向另一种文件,则为False。

    如果该路径不存在或者是已破损的链接,返回False。传播其他错误(例如权限错误)。

Path. iterdir()

    当路径指向目录时,在目录内容匹配路径对象:

>>>p = Path('docs')

>>>for child in p.iterdir(): 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. lchmod(mode)

    类似于Path. chmod(),但是,如果路径指向一个符号链接,将会修改符号链接的模式而非目标的模式。

Path.lstat()

    类似于Path. stat(),但是,如果路径指向一个符号链接,返回符号链接的信息而不是目标的信息。

Path. mkdir(mode=0o777,parents=False, exist_ok=False)

    在给定的路径下创建一个新的目录。如果mode被给出,它会与进程的umask值相结合,以决定文件的模式和访问标志。如果路径早已存在,那么将抛出FileExistsError.

    如果parents为真,该路径如果却是父母且父母是必须的,就会新建父母。它们以默认权限创建而不考虑模式(模仿POSIX MKDIR-P命令)。

    如果parents为假(默认值),父母缺失会抛出FileNotFoundError。

    如果exist_ok为假(默认值),并且目标目录已存在,将会抛出FileExistError。

    如果exist_ok为真,FileExistsError将被忽略(与POSIX MKDIR-P命令相同的行为),但只有在最后一个路径组件不是现有的非目录文件时才例外。

Path. open(mode=’r’,buffering=-1. encoding=None, errors=None, newline=None)

    打开路径指向的文件,其行为类似于内置函数open():

>>>p = Path('setup.py')

>>>with p.open() as f:

...     f.readline()

...

'#!/usr/bin/envpython3\n'

Path.owner()

    返回该用户名所拥有的文件。如果文件的uid没有在系统的数据库中找到,将会抛出KeyError。

Path. read_bytes()

    返回位对象指向文件的二进制内容:

>>>p = Path('my_binary_file')

>>>p.write_bytes(b'Binaryfile contents')

20

>>>p.read_bytes()

b'Binaryfile contents'

Path. read_text(encoding=None,errors=None)

    以字符串的形式返回指定文件的编码内容。

>>>p = Path('my_text_file')

>>>p.write_text('Text filecontents')

18

>>>p.read_text()

'Text filecontents'

    可选参数与open()中的参数含义相同。

Path.rename(target)

    重命名由target指定的文件或目录。在Unix中,如果target存在并且是文件,在用户许可的情况下,他将会被默默取代。target可以是字符串或者是其它路径对象:

>>>p = Path('foo')

>>>p.open('w').write('some text')

9

>>>target = Path('bar')

>>>p.rename(target)

>>>target.open().read()

'sometext'

Path. replace(target)

    重命名target指定的文件或目录。如果target指向了一个存在的文件或目录,它将被无条件替换。

Path.resolve(strict=False)

    使路径转化为绝对路径,转化任何链接。返回一个新的路径对象:

>>>p = Path()

>>>p

PosixPath('.')

>>>p.resolve()

PosixPath('/home/antoine/pathlib')

    “..”组件也会被清理(只有该方法有这种操作):

>>>p = Path('docs/../setup.py')

>>>p.resolve()

PosixPath('/home/antoine/pathlib/setup.py')

    如果路径不存在并且strict为真,将会抛出FiieNotFoundError。如果strict为假,该路径尽可能地被解析,并且在不检查是否存在的情况下追加任何余数。如果沿着分辨率路径遇到无限循环,则会引发运行时错误。

Path. rglob(pattern)

    类似于使用“**”调用Path.glob(),并在其前方添加给定的pattern:

>>>sorted(Path().rglob("*.py"))

[PosixPath('build/lib/pathlib.py'),

 PosixPath('docs/conf.py'),

 PosixPath('pathlib.py'),

 PosixPath('setup.py'),

 PosixPath('test_pathlib.py')]

Path. rmdir()

    移除该目录。目录必须为空。

Path.samefile(other_path()

    返回确定该路径是否与other_path指向同一个文件,不管其为路径对象还是字符串。它的语义与os. path. samefile()和os. path. samestat()相同。

    如果文件因为一些原因无法访问,抛出OSError错误。

>>>p = Path('spam')

>>>q = Path('eggs')

>>>p.samefile(q)

False

>>>p.samefile('spam')

True

Path. symlink_to(target,target_is_directory=False)

    生成一个指向target的符号链接。在Windows下,如果连接的对象是目录,target_is_directory必须为真(默认为假)。在POSIX下,target_is_directory被忽略。

>>>p = Path('mylink')

>>>p.symlink_to('setup.py')

>>>p.resolve()

PosixPath('/home/antoine/pathlib/setup.py')

>>>p.stat().st_size

956

>>>p.lstat().st_size

8

注意:参数(link,target)的顺序与os. symlink()相比是颠倒的。

Path.touch(mode=0o666, exist_ok=True)

    在给定路径创建文件。如果给定模式,则将其与进程的UMASK值相结合,以确定文件模式和访问标志。如果文件已经存在,如果存在SturnOK为真(并且其修改时间被更新到当前时间),则函数将成功,否则将引发FielEnSerSerRor。

Path. unlink()

    移除该文件或符号链接。如果路径指向一个目录,使用Path. rmdir()取代。

Path.write_bytes(data)

    在比特模式下打开文件,向其写入data,之后关闭:

>>>p = Path('my_binary_file')

>>>p.write_bytes(b'Binaryfile contents')

20

>>>p.read_bytes()

b'Binaryfile contents'

    已存在的同名文件将会被覆盖。

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

    在文本模式下打开文件,想起写入data,之后关闭:

>>>p = Path('my_text_file')

>>>p.write_text('Text filecontents')

18

>>>p.read_text()

'Text filecontents'

 

猜你喜欢

转载自blog.csdn.net/zhtysw/article/details/80623767