Doresoom
Doresoom

Reputation: 7448

Python os.path.join() mangling absolute path in Windows

I'm new to Python and I'm trying to access a file with a full path represented by the following:

'X:/01 File Folder/MorePath/Data/Test/myfile.txt'

Every time I try to build the full string using os.path.join, it ends up slicing out everything between the drive letter and the second path string, like so:

import os
basePath = 'X:/01 File Folder/MorePath'
restofPath = '/Data/Test/myfile.txt'
fullPath = os.path.join(basePath,restofPath)

gives me:

'X:/Data/Test/myfile.txt'

as the fullPath name.

Can anyone tell me what I'm doing wrong? Does it have something to do with the digits near the beginning of the base path name?

Upvotes: 0

Views: 731

Answers (1)

kindall
kindall

Reputation: 184161

The / at the beginning of your restofPath means "start at the root directory." So os.path.join() helpfully does that for you.

If you don't want it to do that, write your restofPath as a relative directory, i.e., Data/Test/myfile.txt, rather than an absolute one.

If you are getting your restofPath from somewhere outside your program (user input, config file, etc.), and you always want to treat it as relative even if the user is so gauche as to start the path with a slash, you can use restofPath.lstrip(r"\/").

Upvotes: 3

Related Questions