如何将两个 pathlib.PosixPath 路径合并为一个?

How to join two pathlib.PosixPath paths into one?

我在使用其他方法连接路径时遇到问题,而不仅仅是将它们相加。

Python版本:3.9.0

任务描述:

The user gives the path (/path/to/some/folder), the script found a file in a subfolder of that path (subfolder/filename.ext), but with the wrong extension (ext).

Change the file extension to the correct one (tex) and copy it to the new path (/some/other/path/to/folder) keeping the folder structure (folder/subfolder/) in the path specified by the user (/path/to/some/folder).

有人知道我在哪里犯了错误吗?

import os
from pathlib import Path

input_path = Path('/path/to/some/folder')
file_found_in_input_path = Path('/path/to/some/folder/subfolder/filename.ext')
output_path = Path('/some/other/path/to/folder')
expected = Path('/some/other/path/to/folder/subfolder/filename.tex')
relative_path_to_found_file = Path(str(file_found_in_input_path).replace(str(input_path), '')).with_suffix('.tex')

result = output_path / relative_path_to_found_file                  # Doesn't work
# result = Path.joinpath(output_path, relative_path_to_found_file)  # Doesn't work
# result = os.path.join(output_path, relative_path_to_found_file)   # Doesn't work
# result = f'{output_path}{relative_path_to_found_file}'            # It worked...

print(f'   file_found_in_input_path: {file_found_in_input_path}')
print(f'relative_path_to_found_file: {relative_path_to_found_file}')
print(f'                     result: {result}')
print(f'                   expected: {expected}')

输出:

   file_found_in_input_path: /path/to/some/folder/subfolder/filename.ext
relative_path_to_found_file: /subfolder/filename.tex
                     result: /subfolder/filename.tex
                   expected: /some/other/path/to/folder/subfolder/filename.tex

你的relative_path_to_found_file/subfolder/filename.tex,所以os.path.join认为是绝对路径

您需要从 relative_path_to_found_file 中删除第一个 '/',您将得到正确的结果。

print("wrong = ", os.path.join("/some/other/path/to/folder", "/subfolder/filename.tex"))
print("correct = ", os.path.join("/some/other/path/to/folder", "subfolder/filename.tex"))
wrong =  /subfolder/filename.tex
correct =  /some/other/path/to/folder/subfolder/filename.tex