Home »
Python »
Python Programs
How to fix UnicodeDecodeError when reading CSV file in Pandas with Python?
Learn about the UnicodeDecodeError when reading CSV file, and how to fix it?
Submitted by Pranit Sharma, on April 24, 2022
In pandas, we are allowed to import a CSV file with the help of pandas.read_csv() method. Sometimes, while importing a CSV file we might get the following type of error.
# Importing pandas package
import pandas as pd
# Importing dataset
data1=pd.read_csv('C:\Users\hp\Desktop\Includehelp\mycsv.csv')
Error:
Fixing UnicodeDecodeError Error
The easiest way to fix this error is to provide the actual path of the CSV file inside the read_csv() method. The selection of slash ('\') matters a lot. A path of a file may contain a backslash to represent a folder but when it comes to pass the complete path as a parameter inside the method, we need to use the forward slash ('/') to import the CSV file successfully.
Example:
# Importing pandas package
import pandas as pd
# Importing dataset
data=pd.read_csv('C:/Users/hp/Desktop/Includehelp/mycsv.csv')
# Print the dataset
print(data)
Output:
Sometimes, read_csv() method takes encoding option as a parameter to deal with files in different formats. Try to use encoding= utf-8" to fix the error. Other alternative for encoding="utf-8" is encoding="ISO-8859-1".
Example:
# Importing pandas package
import pandas as pd
# Importing dataset
data=pd.read_csv('C:/Users/hp/Desktop/Includehelp/mycsv1.csv', encoding="utf-8")
# Print the dataset
print(data)
Output:
Python Pandas Programs »