我在使用其他方法連接路徑時遇到了問題,而不是僅僅把它們加在一起。
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_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[/span
# 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}' # 成功了...。
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
結果。/subfolder/filename.tex
預期。/some/other/path/to/folder/subfolder/filename.tex
uj5u.com熱心網友回復:
你的relative_path_to_found_file是/subfolder/filename.tex,所以它是os.path.join opinion中的絕對路徑。
你需要從relative_path_to_found_file中洗掉第一個'/',你將得到正確的結果。
print("wrong ="/span>, os. path.join("/some/other/path/to/folder"/span>, "/subfolder/filename.tex"/span>)
print("correct = ", os.path.join("/some/other/path/to/folder", "subfolder/filename.tex")
wrong = /subfolder/filename.tex
正確 = /some/other/path/to/folder/subfolder/filename.tex
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/331273.html
標籤:
上一篇:SVG圖示的滑鼠移動影片
