Search code examples
pythonpathlib

Control order of pathlib and string concatenation


I have a directory I want to save files to, saved as a Path object called dir. I want to autogenerate files names at that path using string concatenation.

The only way I can get this to work in a single line is just through string concatenation:

dir = Path('./Files')
constantString = 'FileName'
changingString = '_001'

path2newfile = dir.as_posix() + '/' + constantString + changingString

print(path2newfile) # ./Files/Filename_001

... which is overly verbose and not platform independent.

What I'd want to do is use pathlib's / operator for easy manipulation of the new file path that is also platform independent. This would require ensuring that the string concatenation happens first, but the only way I know how to do that is to set a (pointless) variable:

filename = constantString + changingString
path2newfile = dir / filename

But I honestly don't see why this should have to take two lines.

If I instead assume use "actual" strings (ie. not variables containing strings), I can do something like this:

path2newfile = dir / 'Filename' '_001'

But this doesn't work with variables.

path2newfile = dir / constantString changingString
# SyntaxError: invalid syntax

So I think the base question is how do I control the order of operators in python? Or at least make the concatenation operator + act before the Path operator /.

Keep in mind this is a MWE. My actual problem is a bit more complicated and has to be repeated several times in the code.


Solution

  • Just use parentheses surrounding your string contatenation:

    path2newfile = dir / (constantString + changingString)