[Tutor] File reading-(encoding problems)

Ben Finney ben+python at benfinney.id.au
Wed Dec 23 05:28:24 EST 2015


Ratheesh kumar <vrkratheesh at live.com> writes:

> Here is my code..try:
>     data=open('info.txt')

[…]

Please be sure to present the code as distinct lines.

You have posted it as plain text (good), the indentation is preserved
(good). The problem here is that your commentary is mingled with the
program code, so that it's difficult to see where the program begins and
ends.

> Man said:  No you haven't!
> Other Man said:  Yes I have.The characters  ""  got added to the
> contents of my file in the beginning.

And again here, you've somehow got your commentary stuck directly onto
the output example. Please be sure to use one empty line to surround any
code examples or output examples.

> Later identified it as a encoding problem. I cleared the problem by
> adding the encoding arguments when opening the file(
> data=open('info.txt',encoding='utf-8-sig')).Now my question is each
> time do I have to make this change or is there away to make this
> encoding a default one?

Yes, you need to specify the encoding of text, when you input or output
that text as bytes (e.g. in a file). Representing text as bytes is done
with a text encoding, and you must be explicit about that encoding
because guessing the encoding leads to heartache.

Your use of an explicit encoding in that program is correct.

-- 
 \        “I took it easy today. I just pretty much layed around in my |
  `\        underwear all day. … Got kicked out of quite a few places, |
_o__)                              though.” —Bug-Eyed Earl, _Red Meat_ |
Ben Finney



More information about the Tutor mailing list