Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 5941247
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T16:04:59+00:00 2026-05-22T16:04:59+00:00

I wish to write a python program which reads files containing unicode text. These

  • 0

I wish to write a python program which reads files containing unicode text. These files are normally encoded with UTF-8, but might not be; if they aren’t, the alternate encoding will be explicitly declared at the beginning of the file. More precisely, it will be declared using exactly the same rules as Python itself uses to allow Python source code to have an explicitly declared encoding (as in PEP 0263, see https://www.python.org/dev/peps/pep-0263/ for more details). Just to be clear, the files being processed are not actually python source, but they do declare their encodings (when not in UTF-8) using the same rules.

If one knows the encoding of a file before one opens it, Python provides a very easy way to read the file with automatic decoding: the codecs.open command; for instance, one might do:

import codecs
f = codecs.open('unicode.rst', encoding='utf-8')
for line in f:
    print repr(line)

and each line we get in the loop will be a unicode string. Is there a Python library which does a similar thing, but choosing the encoding according to the rules above (which are Python 3.0’s rules, I think)? (e.g. does Python expose the ‘read file with self-declared encoding’ it uses to read source to the language?) If not, what’s the easiest way to achieve the desired effect?

One thought is to open the file using the usual open, read the first two lines, interpret them as UTF-8, look for a coding declaration using the regexp in the PEP, and if one finds one start decoding all subsequent lines using the encoding declared. For this to be sure to work, we need to know that for all the encodings that Python allows in Python source, the usual Python readline will correctly split the file into lines – that is, we need to know that for all the encodings Python allows in Python source, the byte string ‘\n’ always really mean newline, and isn’t part of some multi-byte sequence encoding another character. (In fact I also need to worry about ‘\r\n’ as well.) Does anyone know if this is true? The docs were not very specific.

Another thought is to look in the Python sources. Does anyone know where in the Python source the source-code-encoding-processing is done?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-22T16:05:00+00:00Added an answer on May 22, 2026 at 4:05 pm

    You should be able to roll your own decoder in Python. If you’re only supporting 8-bit encodings which are supersets of ASCII the code below should work as-is.

    If you need support 2-byte encodings like UTF-16 you’d need to augment the pattern to match \x00c\x00o.. or the reverse, depending on the byte order mark.
    First, generate a few test files which advertise their encoding:

    import codecs, sys
    for encoding in ('utf-8', 'cp1252'):
        out = codecs.open('%s.txt' % encoding, 'w', encoding)
        out.write('# coding = %s\n' % encoding)
        out.write(u'\u201chello se\u00f1nor\u201d')
        out.close()
    

    Then write the decoder:

    import codecs, re
    
    def open_detect(path):
        fin = open(path, 'rb')
        prefix = fin.read(80)
        encs = re.findall('#\s*coding\s*=\s*([\w\d\-]+)\s+', prefix)
        encoding = encs[0] if encs else 'utf-8'
        fin.seek(0)
        return codecs.EncodedFile(fin, 'utf-8', encoding)
    
    for path in ('utf-8.txt','cp1252.txt'):
        fin = open_detect(path)
        print repr(fin.readlines())
    

    Output:

    ['# coding = utf-8\n', '\xe2\x80\x9chello se\xc3\xb1nor\xe2\x80\x9d']
    ['# coding = cp1252\n', '\xe2\x80\x9chello se\xc3\xb1nor\xe2\x80\x9d']
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I wish to write a windows app which does something when I become disconnected
I wish to write a query which will replace the value0.00 with - in
I wish to write a function which I can add to my .vimrc file
I sometimes write Python programs which are very difficult to determine how much memory
I have a whole lot of XML files, badly indented. I wish to write
I wish to write JSP which generates XML file, which has syntax, similiar to
I wish to write a simple javascript function that toggles the visibility of a
I wish to write a reusable library for querying against AD with LDAP. I'm
I am using Qt and wish to write a class that will perform some
I wish to know all the pros and cons about using these two methods.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.