Problem opening a text file in Python

It seems to be very simple:

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

But I get 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?

+5
source share
2 answers

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

You can also find useful functions in os.path .

+11
source

Windows . , , , '\ r', '\ t', '\n'... .. . , .

. , r'C:\Users\john\Desktop\text.txt'

+5

All Articles