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 Answers1

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')
>>> 
ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • 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')` – Boris Donnelly Oct 14 '21 at 23:06
  • @BorisDonnelly, use parentheses: `pathlib.Path.home() / "whatever" / ("Force" + "_" + "Bru")` or f-strings: `the_path / f"myfolder_{name}_{surname}" / "other_folder"` – ForceBru Oct 14 '21 at 23:09
  • Should there be space before and after each slashes (`/`)? If yes why there is not any after `home()` – alper Oct 15 '21 at 12:58
  • @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 /"`. – ForceBru Oct 15 '21 at 13:03
  • I was considering for : `pathlib.Path.home() / "Desktop" / "Project_folder"` vs `pathlib.Path.home()/"Desktop"/"Project_folder"` – alper Oct 16 '21 at 13:08
  • @alper, there's absolutely no difference between these because spaces between operators don't matter – ForceBru Oct 16 '21 at 14:50