Search code examples
pythonpathpathlib

Using variable and strings to create name with posixpath


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


Solution

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

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