0

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.

1 Answer 1

2

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')
>>> 
Sign up to request clarification or add additional context in comments.

6 Comments

What if I need the folder name to contain both first_name and second_name, i.e. in your example PosixPath('/.../Desktop/Project_folder/Force_Bru/subfolder')
@BorisDonnelly, use parentheses: pathlib.Path.home() / "whatever" / ("Force" + "_" + "Bru") or f-strings: the_path / f"myfolder_{name}_{surname}" / "other_folder"
Should there be space before and after each slashes (/)? If yes why there is not any after home()
@alper, the slashes are actually division operators. Do you need spaces in 1/2? Python doesn't care - it's just a matter of legibility and code style. Spaces in strings matter very much, though: "hello/" != "hello /".
I was considering for : pathlib.Path.home() / "Desktop" / "Project_folder" vs pathlib.Path.home()/"Desktop"/"Project_folder"
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.