How to import a file in python 3.3.3

I am trying to load an array from another file (for a while now, and I went through a lot of questions about stack overflows), but I cannot get the simplest things to work with. This is one of the errors I received:

>>> 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 did not get this error. He simply could not find the file, although I'm sure it was there, and it was a text file.

Does anyone know what is happening, or if this method no longer works in python 3.3.3?

+3
python file-io
source share
1 answer

The error is not in the file, but in the line file_name . You need to avoid backslashes in your file name; use the raw string:

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

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

You can also double slashes:

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

or use 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 
+2
source share

All Articles