ADVERTISEMENT
ADVERTISEMENT

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:

Fix UnicodeDecodeError | Output 1

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:

Fix UnicodeDecodeError | Output 2

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:

Fix UnicodeDecodeError | Output 3

Python Pandas Programs »



ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.