在Python中處理復雜的路徑通常涉及到對路徑的解析、處理和操作。以下是一些處理復雜路徑的常見方法:
import os
path = "/path/to/some/dir"
new_path = os.path.abspath(os.path.join(path, "file.txt"))
print(new_path)
import os
path = "/path/to/some/dir/file.txt"
dir_name, file_name = os.path.split(path)
file_name, extension = os.path.splitext(file_name)
print(dir_name, file_name, extension)
from pathlib import Path
path = Path("/path/to/some/dir/file.txt")
new_path = path.with_name("new_file.txt")
print(new_path)
通過這些方法,可以更方便地處理復雜的路徑,進行路徑的拼接、解析、操作等操作。