向已经具有 pathlib 后缀的路径添加另一个后缀

对于大多数与路径相关的操作,我将一些旧的 Python 代码转换为使用 pathlib而不是 os.path,但是我最终遇到了以下问题: 我需要向已经有扩展的路径添加另一个扩展(而不是替换它)。对于 os.path,由于我们只是在操作字符串,所以解决方案是添加带字符串运算的扩展:

newpath = path + '.res'

它不能用于 pathlib.Path,因为它不允许任意字符串联。我能找到的最接近的信息如下:

newpath = path.with_suffix(path.suffix + '.res')

它看起来像一个变通方法,因为它最后仍然使用字符串加法。它有一个新的陷阱,因为我一开始忘了处理已经有几个扩展的情况,你想添加一个新的,导致以下代码返回旧的行为:

newpath = path.with_suffix(''.join(path.suffixes) + '.res')

现在它感觉既不简洁也不干净,因为它使用越来越多的字符串运算来实现旧的行为,而不是纯粹的路径操作。Path.suffixes的存在意味着库的开发人员考虑了一个文件可以有多个扩展名的情况,但是我不能找到一种简单地向路径添加新扩展名的方法。还有没有更惯用的方法,我已经错过了实现同样的行为?

编辑: 实际上 path.with_suffix(path.suffix + '.res')已经足够处理已经有几个文件扩展名的情况,即使它对我来说不是很明显。

37463 次浏览

The following code should do what you want it to in a very dynamic way.

from pathlib import Path
import time


p = Path('.')
p = p / '..' / 'Python' / 'Files' / 'Texts_to_read' / 'a_text_file'


new_p = str(p).split('\\')


new_suffix = '.txt'


new_p[-1] = new_p[-1] + new_suffix


p = Path('.')


for x in new_p:
p = p / x


print(new_p)


print(p)
print(str(p))


time.sleep(5)

The fact that normal string operations can be used in this case is a good thing, as it adds a great deal of control over the file path desired without requiring a large assortment of new functions.

It doesn't seem like Path's like being modified in-place (you can't change .parts[-1] directory or change .suffixes, etc.), but that doesn't mean you need to resort to anything too unsavory. The following works just fine, even if it's not quite as elegant as I'd like:

new_path = path.with_suffix(path.suffix + new_suffix)

where path is your original Path variable, and new_suffix is the string with your new suffix/extension (including the leading ".")

You can just convert your Path to string then add new extension and convert back to Path:

from pathlib import Path
first = Path("D:/user/file.xy")
print(first)
second = Path(str(first)+".res")
print(second)

I find the following slightly more satisfying than the answers that have already been given:

new_path = path.parent / (path.name + '.suffix')

if you want to append the file name, but not change the extension, this works

matfile2 = pathlib.Path.joinpath(matfile.parent, matfile.stem+' insert'+matfile.suffix)

You might use pathlib3x - it offers a backport of the latest (at the date of writing this answer Python 3.11.a0) Python pathlib for Python 3.6 or newer, and a few additional functions like append_suffix

>>> python -m pip install pathlib3x


>>> import pathlib3x as pathlib


>>> pathlib.Path('some_path').append_suffix('.ext')
PosixPath('some_path.ext')
>>> pathlib.Path('some_path.ext.ext2').append_suffix('.ext3')
PosixPath('some_path.ext.ext2.ext3')




you can find it on github or PyPi


Disclaimer: I'm the author of the pathlib3x library.

I think this would be better since you just want to extend the current path with an arbitrary string.

old_path = Path("/the/old/path.foo")  # "/the/old/path.foo"
new_path = Path(f"{old_path}.bar")    # "/the/old/path.foo.bar"