如何使用 pathlib.Path.expanduser() 并修改和使用 PosixPath 值?

How to use pathlib.Path.expanduser() and amend and use a PosixPath value?

下面显示了我如何通过 python 3.6 的 os 模块获取 user1 的主目录,创建一个新的子目录名称并在那里创建一个新的子目录。

>>> import os.path
>>> import os
>>> a = os.path.expanduser('~')
>>> a
'/home/user1'
>>> a_sub_dir = a + '/Sub_Dir_1'
>>> a_sub_dir
'/home/user1/Sub_Dir_1'
>>> def create_sub_dir( sub_dir ):
    try:
        os.makedirs( sub_dir, mode=0o777, exist_ok=False )
    except FileExistsError:
        print('Sub_directory already exist, no action taken.')
    else:
        print('Created sub_directory.')
>>> create_sub_dir( a_sub_dir )
Created sub_directory.
>>> create_sub_dir( a_sub_dir )
Sub_directory already exist, no action taken.

我想通过 python 3.6 的 pathlib 模块实现与上述相同的功能。但是,我似乎无法让它工作(见下文)。我的问题:

  1. 如何使用 Path.expanduser()
  2. 如何修改a中的信息 PosixPath(......) 因为它不是字符串所以我可以重复使用它?
  3. 我想修改 PosixPath 并将其用于我的 make_sub_dir() 函数。它会工作吗?目前,我明确地 定义了我要创建的新子目录以检查我的 make_sub_dir() 功能有效。

感谢有关如何使用 pathlib 的指导。提前致谢。

>>> from pathlib import Path
>>> b = Path.expanduser('~')
Traceback (most recent call last):
  File "<pyshell#87>", line 1, in <module>
    b = Path.expanduser('~')
  File "/usr/lib/python3.6/pathlib.py", line 1438, in expanduser
    if (not (self._drv or self._root) and
AttributeError: 'str' object has no attribute '_drv'
>>> b = Path.expanduser('~/')
Traceback (most recent call last):
  File "<pyshell#88>", line 1, in <module>
    b = Path.expanduser('~/')
  File "/usr/lib/python3.6/pathlib.py", line 1438, in expanduser
    if (not (self._drv or self._root) and
AttributeError: 'str' object has no attribute '_drv'
>>> b = Path.home()
>>> b
PosixPath('/home/user1')
>>> b_sub_dir = b + '/Sub_Dir_1'
Traceback (most recent call last):
  File "<pyshell#91>", line 1, in <module>
    b_sub_dir = b + '/Sub_Dir_1'
TypeError: unsupported operand type(s) for +: 'PosixPath' and 'str'
>>> def make_sub_dir( sub_dir ):
    try:
        Path(sub_dir).mkdir(mode=0o777, parents=False, exist_ok=False)
    except FileNotFoundError:
        print('Parent directory do not exist, no action taken.')
    except FileExistsError:
        print('Sub_directory already exist, no action taken.')
    else:
        print('Created sub_directory.')
>>> make_sub_dir( '/home/user1/Sub_Dir_1' )
Sub_directory already exist, no action taken.
>>> make_sub_dir( '/home/user1/Sub_Dir_1' )
Created sub_directory.
>>> make_sub_dir( '/home/user1/Sub_Dir_1' )
Sub_directory already exist, no action taken.

pathlibexpanduseros.path 中的不同:它应用于 Path 对象并且不带参数。如文档中所示,您可以使用:

>>> from pathlib import Path
>>> p = Path('~/films/Monty Python')
>>> p.expanduser()
PosixPath('/home/eric/films/Monty Python')

或与.home()合作:

>>> form pathlib import Path
>>> Path.home()
PosixPath('/home/antoine')

然后为了join directories你应该使用/(而不是+):

b_sub_dir = b / 'Sub_Dir_1'