5

This seems like it should be very easy:

f = open('C:\Users\john\Desktop\text.txt', 'r')

But I am getting this error:

  Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    f = open('C:\Users\john\Desktop\text.txt', 'r')
IOError: [Errno 22] invalid mode ('r') or filename: 'C:\\Users\robejohn\\Desktop\text.txt'

Any thoughts?

2 Answers 2

11

Your file name has backslash characters in it. Backslash is the escape character in Python strings. Either replace them with '/' characters or use r'C:\Users\john\Desktop\text.txt'.

You might also find the functions in os.path useful.

Sign up to request clarification or add additional context in comments.

Comments

5

In Windows, paths use backslash. But if a string that must represent a path contains characters such as '\r' , '\t' , '\n' .... etc there will be this kind of problem. This is the precise reason why your string fails to represent a path.

In the absence of these problematic characters, there will be no problem. If they are present, you must escape the backslashes or use a raw string r'C:\Users\john\Desktop\text.txt'

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.