0

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?

1 Answer 1

3

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"\/").

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, now I feel like an idiot. :) At least I can stop pulling my hair out now. I'll accept when SO lets me after the 10 minute window.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.