franchyze923
franchyze923

Reputation: 1200

Best way to join two paths?

I'm trying to understand the best way to join two paths in Python. I'm able to get my expected result by using string concatenation, but I understand that is not the preferred way of working with paths. I'm trying to preserve the folder structure of a file, but move it to a new defined output directory.

For example -

import os

orig_file = r"F:\Media\Music\test_doc.txt"    
output_dir = r"D:\output_dir"

## preferred method, but unexpected result
new_file = os.path.join(output_dir, os.path.splitdrive(orig_file)[1])
print(new_file)
## new file = D:\Media\Music\test_doc.txt

## What I want
new_file = output_dir + os.path.splitdrive(orig_file)[1]
print(new_file)
## new file = D:\output_dir\Media\Music\test_doc.txt

As you can see, when I use os.path.join() it seems to discard the "output_dir" folder on the D: drive.

Upvotes: 2

Views: 4627

Answers (1)

martineau
martineau

Reputation: 123413

In Python 3.4+, the best way to do it is via the more modern and object-oriented pathlib module.

from pathlib import Path

orig_file = Path(r"F:\Media\Music\test_doc.txt")
output_dir = Path(r"D:\output_dir")
new_file = output_dir.joinpath(*orig_file.parts[1:])
print(f'{new_file=}')  # -> new_file=WindowsPath('D:/output_dir/Media/Music/test_doc.txt')

Upvotes: 3

Related Questions