Using variable and strings to create name with posixpath

700 views Asked by At

I want to create a path with python pathlib using a variable.

This is of course incorrect due to mixing of string and posixpath:

from pathlib import Path
stringvariable='aname'

Path(Path.cwd() / 'firstpartofname_' +stringvariable+ '.csv')

I know I could do it with os, or in two lines like this:

filename='firstpartofname_' + stringvariable + '.csv'
Path(Path.cwd() / filename)

but I want to learn how to use it directly with Path. Thanks

1

There are 1 answers

1
tripleee On BEST ANSWER

You just need to add parentheses to force the + to happen before the /.

new = Path.cwd() / ('firstpartofname_' + stringvariable + '.csv')