1

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

2 Answers 2

2

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

new = Path.cwd() / ('firstpartofname_' + stringvariable + '.csv')
Sign up to request clarification or add additional context in comments.

1 Comment

:-) I cannot have you sleepless nights, so I fixed the spelling :-D
0

you can solve it by making the right hand item a single f-string (all recent python versions do support that).

new = Path.cwd() / f"firstpartofname_{stringvariable}.csv"

Comments

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.