如何连接两个路径库.PosixPath路径合并为一个?



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

Python版本:3.9.0

任务描述:

用户给出了路径(/path/to/some/folder),脚本在该路径(subfolder/filename.ext)的子文件夹中找到了一个文件,但是扩展名(ext)错误。

将文件扩展名更改为正确的(tex)并将其复制到新路径(/some/other/path/to/folder)中,保持文件夹结构(folder/subfolder/)在用户指定的路径(/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

最新更新