Home > database >  Define path using string value with pathlib
Define path using string value with pathlib

Time:10-15

I am trying to design a function that iterates over a script. The arguments of this function are first_name and 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.

CodePudding user response:

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