2
 f = open("‪C:\Users\aleed_000\Desktop\dis.txt","r")
 print (f.read())
 f.close()

Can anyone explain why this doesn't read from my file named dis.txt? When I tried to run it, it says error, and then highlights the open paren. I don't understand what is wrong.

1
  • 2
    Please post the whole traceback. Commented Jun 30, 2013 at 17:20

1 Answer 1

4

Use a raw string or escape each '\' by prefixing another '\' to it:

because C:\Users\aleed_000\Desktop\dis.txt is actually interpreted like this:

>>> print ("‪C:\Users\aleed_000\Desktop\dis.txt") # '\a' gets escaped
C:\Usersleed_000\Desktop\dis.txt

Raw string:

>>> print (r"‪C:\Users\aleed_000\Desktop\dis.txt")  #notice the r at the start
C:\Users\aleed_000\Desktop\dis.txt

Escape each '\':

>>> print ("‪C:\\Users\\aleed_000\\Desktop\\dis.txt")
C:\Users\aleed_000\Desktop\dis.txt
Sign up to request clarification or add additional context in comments.

3 Comments

Or escape every \ character: "‪C:\\Users\\aleed_000\\Desktop\\dis.txt". Each solution works fine :)
When I use the first piece of code (the example print code) I get SyntaxError: invalid character in identifier, when is of course not what you got
@user2317745 Please post that in the question body.

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.