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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Shivkumar kondi
  • 6,458
  • 9
  • 31
  • 58
  • \r is a carriage return character; it tells your terminal emulator to move the cursor at the start of the line – depperm Jun 21 '17 at 15:25
  • 1
    define `b` as `b = r'e$\research'` and then just do `os.path.join(a,b)`. It should be enough – Ma0 Jun 21 '17 at 15:26
  • 1
    See [this question](https://stackoverflow.com/questions/2081640/what-exactly-do-u-and-r-string-flags-do-in-python-and-what-are-raw-string-l) for more details about raw string literals. – Aran-Fey Jun 21 '17 at 15:26
  • I have updated my output: it should be \\ at start – Shivkumar kondi Jun 21 '17 at 15:57

2 Answers2

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
Wondercricket
  • 7,651
  • 2
  • 39
  • 58
  • Thanks .. but I need \\ at start of string – Shivkumar kondi Jun 21 '17 at 16:03
  • @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 – Wondercricket Jun 21 '17 at 16:15
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')
athul.sure
  • 328
  • 5
  • 14