-2

I have the following code:

#!/usr/bin/python

import os
from sys import exit as EXIT


File = os.path.realpath(__file__)
dir = os.path.dirname(File)
os.chdir(dir)
path_file = os.path.join(dir,"path.txt")
filo = open(path_file)
lines = filo.readlines()

if len(lines) == 1:
    path = lines[0]
else:
    raw_input("Too many lines... ")
    EXIT()

FILE = open(path)

When I run it I get error:

Traceback (most recent call last):
  File "py/Zebra/zebra.py", line 20, in <module>
    FILE = open(path)
IOError: [Errno 2] No such file or directory: 'C:\\Users\\user\\file.txt'

If the path would be hard-coded then I could do something like path = r"C:\path\to\file"

But since the variable was defined by other methods, I am not sure now to fix this :(

user324747
  • 255
  • 3
  • 16
  • 3
    I think your problem is not related to the raw string - the escape of backslashes looks correct. – dspencer Apr 01 '20 at 02:28
  • 2
    Does the file definitely exist at that path? – dspencer Apr 01 '20 at 02:34
  • From the first line I will assume you're running Linux. `'C:\\Users...'` should not exist on a Linux system and thus it is not able to find it. If it is so, can you try a valid path and see if the error continues? – XPhyro Apr 01 '20 at 02:40

1 Answers1

1

The idea behind r' ' is to write raw string literals, because it changes the way python escape characters. If it happens to be a value from a variable, as you stated above, you don't need to use r' ' because you are not explicitly writing a string literal.

Either way, I think this will do:

path = r'%s' % pathToFile

EDIT: Also, as commented to the question, you should really be sure the path exists.

DarK_FirefoX
  • 887
  • 8
  • 20