Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to import a file in python 3.3.3 [duplicate]

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?

like image 369
thegunmaster Avatar asked May 19 '26 20:05

thegunmaster


1 Answers

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
like image 120
Martijn Pieters Avatar answered May 21 '26 15:05

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!