• Register
0 votes
834 views

Problem :

I want to read my .csv file into Python (Spyder) but I am facing the error.

Please find below my code :

import csv
mydata = open("C:\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener")
mydata = csv.reader(mydata)  
print(mydata)

I face the following error:

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

7.5k points

Please log in or register to answer this question.

2 Answers

0 votes

Solution :

The String literals can be enclosed within either the single quotes (i.e. '...') or the double quotes (i.e. "..."). They can also be enclosed in the matching groups of either three single or double quotes (these are usually referred to as triple-quoted strings).

The backslash character (i.e. \) can be used to escape the characters which otherwise will have a special meaning, such as the newline, backslash itself, or the quote character. String literals may be optionally prefixed with a letter either r or R. Such strings are called as raw strings and used in different rules for the backslash escape sequences.

In the triple-quoted stringsunescaped newlines and quotes both are allowed , except that the three unescaped quotes in the row terminate the string.

Unless an r or R prefix is present, the escape sequences in strings are interpreted according to rules similar to be used by Standard C.

38.6k points
0 votes

Solution:

Since it is an escape failure, the simplest solution is not to use “escape”.

Solution 1: Add a “r” character in the beginning of string.

title = r'\uFFEF'

In Python, when we add a “r” character, it’s meaning a complete string.

Solution 2: Change “\” to be “/”.

open("C:\Users\Clay\Desktop\test.txt")

Change to:

open("C:/Users/Clay/Desktop/test.txt")

Solution 3: Change “\” to be “\\”.

open("C:\Users\Clay\Desktop\test.txt")

To be:

open("C:\\Users\\Clay\\Desktop\\test.txt")

This error occurs because you are using a normal string as a path. You can use one of the following solutions to fix your problem.

1. Just put r before your normal string it converts normal string to raw string:
pandas.read_csv(r"C:\Users\DeePak\Desktop\myac.csv")

2.

pandas.read_csv("C:/Users/DeePak/Desktop/myac.csv")

3.

pandas.read_csv("C:\\Users\\DeePak\\Desktop\\myac.csv")

 

31.7k points