Fix the Unicodeescape Error when Specifying a Path in Python

When specifying a file path in Python, you may face the following unicodeescape error if the path contains backslashes:

SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in position 2-3: truncated \UXXXXXXXX escape

In this short guide, you’ll see two ways to overcome this error.

Two ways to fix the unicodeescape error

(1) Place “r” before the path string

For example, here we have a simple script to import a CSV file called products:

import pandas as pd

data = pd.read_csv("C:\Users\Ron\Desktop\Test\products.csv")   
df = pd.DataFrame(data)

print(df)

If we run the script in Python, we’ll get the following error:

SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in position 2-3: truncated \UXXXXXXXX escape

To overcome this error, we can place the “r” letter before the path string. This prevents Python from interpreting backslashes as escape sequences:

import pandas as pd

data = pd.read_csv(r"C:\Users\Ron\Desktop\Test\products.csv")   
df = pd.DataFrame(data)

print(df)

If we run the script, the file would be imported correctly.

    product brand  price
0  Computer     A   1200
1    Tablet     B    350
2   Printer     C    120
3   Monitor     D    400
4  Keyboard     E     80

(2) Use double backslashes in the path string

Alternatively, we can use double backslashes in the path for every instance where a single backslash was originally present:

import pandas as pd

data = pd.read_csv("C:\\Users\\Ron\\Desktop\\Test\\products.csv")   
df = pd.DataFrame(data)

print(df)

The result:

    product brand  price
0  Computer     A   1200
1    Tablet     B    350
2   Printer     C    120
3   Monitor     D    400
4  Keyboard     E     80

Leave a Comment