Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join paths nice way?

Tags:

python

path

What I have:

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
filepath = 'files/one.txt'
request_path = os.path.join(BASE_DIR, filepath)
print(request_path, filepath, BASE_DIR)

And it prints

/files/one.txt /files/one.txt /home/pavel/Dev/AiPOSiZI/Lab_1

what means paths weren't joined.

But

os.path.join('/home/pavel/Dev/AiPOSiZI/Lab_1/', 'files/one.txt')

(I've added / to the end of /home/... and removed / from the beginning of /files/...) works well.

I could just manually add and remove / from paths but I wonder if there is any more elegant way to join them

like image 820
Pavel Antspovich Avatar asked Oct 22 '25 04:10

Pavel Antspovich


1 Answers

On python 3.8.0 it seem to work as expected.

import os

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

filepath = 'files/one.txt'
request_path = os.path.join(BASE_DIR, filepath)
print(request_path, filepath, BASE_DIR)
$ python -V
Python 3.8.0
$ python /tmp/a.py
/tmp/files/one.txt files/one.txt /tmp
like image 133
shantanoo Avatar answered Oct 24 '25 18:10

shantanoo