2

I want to get a path location as ' \\BIWDB02\e$\research' using os.join.path

I tried these ways

 import os
 a = 'BIWDB02'
 b = 'e$\research'
 c = '\\\\'
 print c
    # \\

Try-1:

x = os.path.join('\\','\\',a,b)
print x

output:

 \BIWDB02\e$
    esearch

Don't know why it is coming on next line and even 'r' is missing.

Try-2 ,3

y = os.path.join('\\\\',a,b)
print y

z= os.path.join(c,a,b)
print z

Error:

IndexError: string index out of range

Update:

os.path.join('\\\\\\',a,b)
#\\\BIWDB02\e$\research

with 6-\\\ it gives me 3-\\ but with 4-\\ it gives me indexError again.

4
  • \r is a carriage return character; it tells your terminal emulator to move the cursor at the start of the line Commented Jun 21, 2017 at 15:25
  • 1
    define b as b = r'e$\research' and then just do os.path.join(a,b). It should be enough Commented Jun 21, 2017 at 15:26
  • 1
    See this question for more details about raw string literals. Commented Jun 21, 2017 at 15:26
  • I have updated my output: it should be \\ at start Commented Jun 21, 2017 at 15:57

2 Answers 2

5

The issue is coming from the \r in e$\research. \r is know as a carriage return and performs a return newline.

Add r to e$\research to make it a raw string literals

import os
a = 'BIWDB02'
b = r'e$\research'
c = '\\\\'
x = os.path.join(c, a, b)
print x

>>> \\BIWDB02\e$\research
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks .. but I need \\ at start of string
@BHappyBHarsham I updated my answer. I noticed in your update, you said \\\\ gives you an IndexError. Which version of python are you running? I tested my update in 2.7 and 3.5 and I did not receive the error
0

You don't have to manually escape your path names. You can cast them as raw strings in Python 2.x as follows:

"Path with lots of tricky characte\rs.\n..durr".encode('string-escape')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.