将另一个后缀添加到已经具有pathlib后缀的路径中 [英] Adding another suffix to a path that already has a suffix with pathlib
问题描述
我正在转换一些旧的Python代码,以使用 pathlib
代替os.path
用于大多数与路径相关的操作,但最终出现以下问题:我需要向已具有扩展名的路径中添加另一个扩展名(而不是替换它).使用os.path
,由于我们仅处理字符串,因此解决方案是使用字符串操作添加扩展名:
I was converting some old Python code to use pathlib
instead of os.path
for most path-related operations, but I ended up with the following problem: I needed to add another extension to a path that already had an extension (not replace it). With os.path
, since we are merely manipulating strings, the solution was to add the extension with string operations:
newpath = path + '.res'
它不适用于pathlib.Path
,因为它不允许串联任意字符.我能找到的最接近的是:
It doesn't work with pathlib.Path
because it doesn't allow concatenation of arbitrary characters. The closest I could find was the following:
newpath = path.with_suffix(path.suffix + '.res')
这似乎是一种解决方法,因为它最后仍然使用字符串加法.它有一个新的陷阱,因为我首先忘了处理已经有几个扩展名而您想添加一个新扩展名的情况,导致以下代码恢复了旧的行为:
It looks like a workaround because it still uses string addition in the end. And it has a new pitfall because I forgot at first to handle the case where there are already several extensions and you want to add a new one, leading to the following code to get back the old behaviour:
newpath = path.with_suffix(''.join(path.suffixes) + '.res')
现在它既不简洁也不干净,因为它使用越来越多的字符串操作来实现旧的行为,而不是单纯的路径操作. Path.suffixes
存在的事实意味着该库的开发人员考虑了文件可以具有多个扩展名的情况,但是我找不到简单地将新扩展名添加到路径的方法.为了实现相同的行为,我还想念一种更惯用的方式吗?
Now it doesn't feel terse nor clean since it uses more and more string operations to achieve the old behaviour instead of pure path operations. The fact that Path.suffixes
exists means that the library's developers considered the case where a file can have multiple extensions, yet I couldn't find a way to simply add a new extension to a path. Is there a more idiomatic way that I have missed to achieve the same behaviour?
实际上path.with_suffix(path.suffix + '.res')
足以应付已经有多个文件扩展名的情况,即使这对我来说不是很明显.
actually path.with_suffix(path.suffix + '.res')
is enough to handle the case where there are already several file extensions, even though it wasn't immeditely obvious to me.
推荐答案
我发现以下内容比已经给出的答案更加令人满意:
I find the following slightly more satisfying than the answers that have already been given:
new_path = path.parent / (path.name + '.suffix')
这篇关于将另一个后缀添加到已经具有pathlib后缀的路径中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!