下面显示了我如何获取 user1 的主目录,创建一个新的子目录名称并通过 python 3.6 的os模块在那里创建一个新的子目录。
>>> 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.
Run Code Online (Sandbox Code Playgroud)
我想通过 python 3.6 的pathlib模块实现与上面相同的功能。但是,我似乎无法让它工作(见下文)。我的问题:
Path.expanduser()? 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.
Run Code Online (Sandbox Code Playgroud)
pathlib's 的expanduser工作方式与 in 不同os.path:它应用于Path对象并且不接受任何参数。如文档中所示,您可以使用:
>>> from pathlib import Path
>>> p = Path('~/films/Monty Python')
>>> p.expanduser()
PosixPath('/home/eric/films/Monty Python')
Run Code Online (Sandbox Code Playgroud)
或与.home():
>>> form pathlib import Path
>>> Path.home()
PosixPath('/home/antoine')
Run Code Online (Sandbox Code Playgroud)
然后为了加入目录,您应该使用/(而不是+):
b_sub_dir = b / 'Sub_Dir_1'
Run Code Online (Sandbox Code Playgroud)