473,785 Members | 2,488 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Reading in a UTF-8 file but causing a UnicodeDecodeEr ror exception

92 New Member
I have a CSV file created by VisualBasic in UTF-8. If I open the file in vi/emacs I see the Byte-Order marker (BOM), <feff>


So now when I read the file:

Expand|Select|Wrap|Line Numbers
  1. import codecs
  2. f = open ('myfile')
  3. test = f.readline ()
  4. print test.decode ('utf-8')
  5.  
It prints a control character (u'\u\xef\xbb\x bf) as its first character. Shouldn't the decode strip this? Also tried the following to see what would happen and try to auto-detect the format:

Expand|Select|Wrap|Line Numbers
  1. import codecs
  2. for encoding in ['utf-8', 'utf-16']:
  3.     try:
  4.             f = codecs.open ('myfile', encoding=encoding)
  5.             test = f.readline ()
  6.             test
  7.     except Exception, exc:
  8.             f = None
  9.             print (exc)
  10.  
For UTF-16 this is weird cause it states "UTF-16 stream does not start with BOM" even though the first char is the BOM. For UTF-8 no errors but it prints the control characters (u'\ufeff)

Any ideas what is going on with this? Possibly a badly encoded file?
Aug 11 '09 #1
3 7974
Benny the Guard
92 New Member
More context. I loaded the file in emacs with hex mode and I see efbbbf which should indicate UTF-8. So the questions are:

1. Why does vi show '<feff>' as the first char?
2. Why does the first code snipet I show not strip the control character?
3. Why when using codecs.open and forcing UTF-8 does it replace the control charcater with feff?
4. Does Python have a way to read in a file with auto-detection for encoding?
Aug 11 '09 #2
bvdet
2,851 Recognized Expert Moderator Specialist
Evan Jones has a good explanation here. I did a little test on my system reading a UTF-8 file with Python 2.3.
Expand|Select|Wrap|Line Numbers
  1. #UTF-8
  2. s1 = open('unicode_example1.txt', 'r').read()
  3. print repr(s1.decode("UTF-8"))
  4. if s1.startswith(codecs.BOM_UTF8):
  5.     s1 = s1.lstrip(codecs.BOM_UTF8)
  6. print repr(s1)
And the output:
Expand|Select|Wrap|Line Numbers
  1. >>> u'abcdef'
  2. 'abcdef'
Apparently object s1 is now a simple string.

Expand|Select|Wrap|Line Numbers
  1. >>> s1
  2. 'abcdef'
  3. >>> unicode(s1, 'UTF-8')
  4. u'abcdef'
  5. >>> 
Aug 12 '09 #3
Benny the Guard
92 New Member
Thanks! This helps alot. I agree with Evan that this seems like a bug in Python coedecs, in that it strips the BOM from UTF-16 but not UTF-8. But adding:

lstrip ( unicode( codecs.BOM_UTF8 , "utf8" ) )

Works wonders. Had to use the unicode stuff to avoid an excpetion due to non-ascii characters, but it now works nicely.
Aug 12 '09 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

9
4192
by: lawrence | last post by:
Someone on www.php.net suggested using a seems_utf8() method to test text for UTF-8 character encoding but didn't specify how to write such a method. Can anyone suggest a test that might work? Something that maybe gives 90% confidence that a given block of text is or is not UTF-8 encoded?
38
5739
by: Haines Brown | last post by:
I'm having trouble finding the character entity for the French abbreviation for "number" (capital N followed by a small supercript o, period). My references are not listing it. Where would I find an answer to this question (don't find it in the W3C_char_entities document). -- Haines Brown brownh@hartford-hwp.com
1
3653
by: Ldaled | last post by:
Okay, I had a previous post called reading an XML document. Since this post I have revised my code and got it to work. Now, Like Derek had mentioned in answer to my previous post, I am getting an XmlException. The error message is invalid date SEMICOLON expected at Line 1 Position 380. Derek you had said something about the UTF encoding attribute in the xml declaration, it is in fact UTF-8. So if this is my problem or what is causing the...
23
5029
by: Allan Ebdrup | last post by:
I hava an ajax web application where i hvae problems with UTF-8 encoding oc chineese chars. My Ajax webapplication runs in a HTML page that is UTF-8 Encoded. I copy and paste some chineese chars from another HTML page viewed in IE7, that is also UTF-8 encoded (search for "china" on google.com). I paste the chineese chars into a content editable div. My Ajax webservice compiles an XML where the data from the content editable div is...
4
17741
by: Peted | last post by:
hello, i have a app.config file like so <?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="rdbUser1Cpu1" value="Cpu1,test"/> </appSettings> </configuration>
1
2549
by: tamoochin | last post by:
I have a form that registers the user with my website, the form is in farsi language and must use utf-8 standard. I can store data in MS Access and also read it back with any problems. the characters are correct in database too. but when I want to search a user in my asp search form, the "not found" phrase displayed! any keyword I use to search like username or name or city will fail. but when I edit the user profile with my asp edit...
7
6847
by: Elliot | last post by:
My XML is using encoding UTF-8 and its content contains Chinese character. When debug the following codes: string strXmlFile = "xml.xml"; XmlDocument objXml = new XmlDocument(); objXml.Load(strXmlFile); It returns "Invalid character in the given encoding" and point to objXml.Load(strXmlFile);.
0
1477
by: moorcroft | last post by:
Hi I have an XML SOAP response which starts with the following XML: <?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <GetAppXmlResponse xmlns="http://***.***.gov.uk/***"> <GetAppXmlResult> <Connector timestamp="9/26/2008 10:46:26 AM" xmlns=""> <code>0</code>...
2
1970
by: moorcroft | last post by:
Hi I have an XML SOAP response which starts with the following XML: <?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <GetAppXmlResponse xmlns="http://***.***.gov.uk/***"> <GetAppXmlResult> <Connector timestamp="9/26/2008 10:46:26 AM" xmlns=""> <code>0</code>...
1
4158
by: quddusaliquddus | last post by:
Hi :D, I am sending data to server via TCP IP Connection. I am using a continuous loop at the server end - that accepts new clients and while streams can be read, it reads data stream. The data is sent from the client with 2 leading bytes of data that represent the size of the packet of data sent and type of data. My question is: how do I retrieve the size of the data packet and then check that this amount of data has been...
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10325
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10091
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9950
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8972
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7499
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6739
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2879
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.