About this question
I'm trying to write a to a csv file, I get the following error:
UnicodeEncodeError: 'ascii' codec can't encode character u'u03b1' in position 20: ordinal not in range(128)
Line causing error:
df.to_csv('out.csv')
I'm trying to write a to a csv file, I get the following error:
UnicodeEncodeError: 'ascii' codec can't encode character u'u03b1' in position 20: ordinal not in range(128)
Line causing error:
df.to_csv('out.csv')
Log in to share your answer and help other learners.
Log in to answerBest Answer · By JanBask Python Expert
Answered on Apr 18, 2021
ordinal not in range(128)
Answer: As the error message “ordinal not in range(128)” suggests the error is being caused because of encoding. Now this could simply be an error because of encoding or it could be because the separator is incorrect.
In csv files all values are separated by commas, but that's not always the case. Sometimes people also use other separators like tabs etc.
Also for a computer to be able to understand text written in a file, it is written in a special computer understandable code. This special code used to be ASCII but now is unicode used most predominantly (utf-8, utf-16 etc).
So either the encoding is incorrect or the separators are incorrect.
You can resolve this error by specifying these details in the to_csv method like this:
df.to_csv(file_name, sep='\t', encoding='utf-8')Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.
Most-read guides across JanBask
Common Python interview questions, answered
Guides, tips and career advice on Python from JanBask experts.
Python How to Become a Python Developer: A Step-by-Step Guide for Beginners
Discover how to become a Python Developer via a practical 7-step guide build projects, maintain clean code, practice daily, and…
Python PCEP Certification Guide: Entry-Level Python Programmer Certification
Explore this PCEP certification guide for insights on cost, exam format, passing score, application, training, and study tips.…
Python Top 50+ Python Projects ideas for Beginners to Advanced
Discover innovative Python project ideas, explore advanced Python projects, and find good Python projects for beginners and…
Python How To Comment Out Multiple Lines In Python Like A Pro
Commenting out code is a common practice among programmers. It allows you to temporarily disable parts of your code without…