简体   繁体   English

pathlib 和字符串连接的控制顺序

[英]Control order of pathlib and string concatenation

I have a directory I want to save files to, saved as a Path object called dir .我有一个我想将文件保存到的目录,保存为一个名为dirPath对象。 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.我想要做的是使用 pathlib 的/运算符来轻松操作同样与平台无关的新文件路径。 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?所以我认为基本问题是如何控制python中运算符的顺序? Or at least make the concatenation operator + act before the Path operator / .或者至少让连接运算符+在路径运算符/之前起作用。

Keep in mind this is a MWE.请记住,这是一个 MWE。 My actual problem is a bit more complicated and has to be repeated several times in the code.我的实际问题有点复杂,必须在代码中重复几次。

只需在字符串连接周围使用括号:

path2newfile = dir / (constantString + changingString)

Have you considered using Python f-strings?你考虑过使用 Python f-strings 吗?

It seems like your real-world example has a "template-y" feel to it, so something like:看起来你的真实世界的例子有一种“模板-y”的感觉,所以像:

path / f"constant part {variable_part}"

may work.可能工作。

Use os.path.join() .使用os.path.join()
It's both platform-independent and you can plug the desired path parts as arguments.它与平台无关,您可以将所需的路径部分作为参数插入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM