My String is giving "unicodeescape" error

-1

I'm trying to open a file with .txt data in Python but an error message appears.

arq = open('C:\Users\Cintia\Documents\Python\Dados\lbe.txt', 'r')
lbe = arq.read()
print(lbe)
arq.close()

The error is unicodeescape .

    
asked by anonymous 30.10.2017 / 13:20

3 answers

2

The path of a file in Windows generates a conflict in Python because of the backslash. When you use C:\Users , Python will interpret the \U character as an escaped U, similar to what happens with \n to break line.

In order to get around this error, you need to prefix the string with a r , to tell the Python interpreter that the string should be analyzed "raw" ( the r is of raw string ), thus:

arq = open(r'C:\Users\Cintia\Documents\Python\Dados\lbe.txt', 'r')
    
30.10.2017 / 13:24
2

The problem is with the string 'C:\Users\Cintia\Documents\Python\Dados\lbe.txt' .

\U An 8-character Unicode escape starts, and as it is succeeded by s , which is an invalid string, it bursts the error. The same would happen with other sequences, such as \r

30.10.2017 / 13:24
0

The problem might be in \ U of "C: \ Users", Maybe you should mention that the path is a rawstring. Try some of the options below:
Example 1:

arq = open(r'C:\Users\Cintia\Documents\Python\Dados\lbe.txt', 'r')

Or else:

arq = open'''C:\Users\Cintia\Documents\Python\Dados\lbe.txt''', 'r')
    
30.10.2017 / 13:26