Home »
Python »
Python Programs
How to fix UnicodeDecodeError when reading CSV file in Pandas with Python?
In this tutorial, we will learn about the UnicodeDecodeError when reading CSV file in Python, and how to fix it?
By Pranit Sharma Last updated : April 19, 2023
UnicodeDecodeError while reading CSV file
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:
Fixing UnicodeDecodeError Error by Specifying `encoding` Parameter
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 »