[英]Define path using string value with pathlib
I am trying to design a function that iterates over a script.我正在尝试设计一个迭代脚本的函数。 The arguments of this function are
first_name
and second_name
.此函数的参数是
first_name
和second_name
。 Among other things, this loop should create folders and subfolders as follows:除其他外,此循环应按如下方式创建文件夹和子文件夹:
def script(first_name='', second_name=''):
(...)
first_name='first_name'
second_name='second_name'
project_path = pathlib.Path.home()/'Desktop/Project_folder'
name_path = pathlib.Path.home()/'Desktop/Project_folder/'+first_name+second_name
subfolder = pathlib.Path.home()/'Desktop/Project_folder/'+first_name+second_name+'/subfolder'
(...)
However, when I try to run the script, I get the following error when creating the folders:但是,当我尝试运行脚本时,在创建文件夹时出现以下错误:
script(first_name, second_name)
(...)
>>> TypeError: unsupported operand type(s) for +: 'WindowsPath' and 'str'
Since I am not very experienced with the pathlib
module, I was wondering whether there was a way to fix this and create folders using string values inside pathlib without specifying the full path in advance.由于我对
pathlib
模块不是很有经验,我想知道是否有办法解决这个问题并使用 pathlib 中的字符串值创建文件夹,而无需事先指定完整路径。
Paths are specified using forward slashes:路径使用正斜杠指定:
pathlib.Path.home()/'Desktop/Project_folder' / first_name / second_name / 'subfolder'
Example:例子:
>>> import pathlib
>>> first_name, second_name = "Force", "Bru"
>>> pathlib.Path.home()/'Desktop/Project_folder' / first_name / second_name / 'subfolder'
PosixPath('/.../Desktop/Project_folder/Force/Bru/subfolder')
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.