-2

I have a text file with a path that goes like this:

r"\\user\data\t83\rf\Desktop\QA"

When I try to read this file a print a line it returns the following string, I'm unable to open the file from this location:

'r"\\\\user\\data\\t83\\rf\\Desktop\\QA"\n'
krakowi
  • 583
  • 5
  • 17

2 Answers2

1

Seems you've got Python code in your text file, so either sanitize your file, so it only includes the actual path (not a Python string representation) or you can try to fiddle with string replace until you're satisfied, or just evaluate the Python string.

Note that using eval() opens Padora's box (it as unsafe as it gets), it's safer to use ast.literal_eval() instead.

import ast
file_content = 'r"\\\\user\\data\\t83\\rf\\Desktop\\QA"\n'
print(eval(file_content)) # do not use this, it's only shown for the sake of completeness
print(ast.literal_eval(file_content))

Output:

\\user\data\t83\rf\Desktop\QA        
\\user\data\t83\rf\Desktop\QA   

Personally, I'd prefer to sanitize the file, so it only contains \\user\data\t83\rf\Desktop\QA

Mike Scotty
  • 10,530
  • 5
  • 38
  • 50
  • Thanks Mike. I got your point. Managed to read the paths and list files within the directories. – krakowi Jul 27 '22 at 13:10
0

\ will wait for another character to form one like \n (new line) or \t (tab) therefore a single backslash will merge with the next character. To solve this if the next character is \\ it will represent the single backslash.

Gamopo
  • 1,600
  • 1
  • 14
  • 22
  • \ works as an escape character to escape next character. – GodWin1100 Jul 27 '22 at 10:37
  • Ok, so I used pth.replace(r'\\', ''), which I print and looks more like a python path now: r"\\user\data\t83\rf\Desktop\QA Then I pass it to open() function. and what I see? I see OSError: [Errno 22] Invalid argument: 'r"user\\data\\t83\\rf\\Desktop\\QA' I really don't understand what is happening here. – krakowi Jul 27 '22 at 10:53