3

I am trying to load a array from another file(for a while now, and have been going through a lot of Stack Overflow Questions), but I can't get the easiest things to work. This is one of the errors I got:

 >>> inp = open ('C:\Users\user\Documents\w-game\run\map1.txt','r')
 SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes 
 in position 2-3:       truncated \UXXXXXXXX escape

Sometimes I didn't get that error. It simply couldn't find the file, although I am sure it was there and it was a text file.

Does anybody know what is up or if this method doesn't work in python 3.3.3 anymore?

thegunmaster
  • 265
  • 4
  • 14

1 Answers1

2

The error is not in the file, but in the filename string. You need to escape the backslashes in your filename; use a raw string:

open(r'C:\Users\user\Documents\w-game\run\map1.txt')

because \Uhhhhhhhh is a unicode escape code for a character outside of the BMP.

You can also double the slashes:

open('C:\\Users\\user\\Documents\\w-game\\run\\map1.txt')

or use forward slashes:

open('C:/Users/user/Documents/w-game/run/map1.txt')

Demo:

>>> print('C:\Users')
  File "<stdin>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
>>> print(r'C:\Users')
C:\Users
>>> print('C:\\Users')
C:\Users
>>> print('C:/Users')
C:/Users
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • I think that forward slashes are the best, because they are more cross platform. Maybe not in this example, but in a relative path the should work both on Windows and Unix. – cubuspl42 Dec 24 '13 at 12:29