python33, windows, UnicodeEncodeError: 'charmap' codec can't encode characters in position, to print out the file contents to stdout,

Rick Johnson rantingrickjohnson at gmail.com
Sun Jul 6 16:52:02 CEST 2014


On Sunday, July 6, 2014 4:05:10 AM UTC-5, gintare wrote:
> The correct code:
> f=open(<snip-path>,'r', encoding='utf-8')
> linef=f.readlines()
> print(repr(linef))

Yes but do you understand why? And even if you DO understand
why, you should explain the details because the neophytes
are always watching!

    >_>
    
    <_<
    
    o_O? ...what, me worry?

Now don't misunderstand me, i am happy that you took the
time to report to us that you found the answer! Yes, nothing
is more aggravating than writing a long, thoughtful, and
elegant answer, and then have the OP come back and say:

    "Oh i found the answer, but thanks anyway"
    
But really, kudos to you for at least making the effort to
report. Because the only thing worse than a report without
context is no report at all! Indeed, then we end up with
unresolved threads and our community mojo suffers.... but i
digress!


Now, we must explain WHY this new code works, and WHY the
old code failed.

    SIMPLE!
    
"file.readlines()" returns a list, with each value of the list
representing a line of the file. Nothing wrong with using
"readlines()" of course, UNTIL you try to pass the value of
"readlines" into the "print()" function, ah-aH-AH! 

So the direct reason for failure is due to the fact that the
"print()" function ONLY handles strings, not list objects.

So in light of this problem there are a few solutions:

  1. Cast the list into a string, which you did using the
  "repr()" function, although you can also use the "str()"
  function, or use "string formatting" if formatting makes
  sense (in this case formatting does not make sense).
  
  2. Use a different method of the file object which returns
  a string instead of a "list-of-lines". Your code seems to
  make no use of "line-ified-data-structures", so why
  burn cycles creating one?

PS: We could use a few more members of the female persuasion
in this community, so thanks for dropping by and hope to see
you posting in the future! We desperately need something
"fair" to offset the reeking of smelly socks, stinky
armpits, and the stomach churning *stench* of illogical
naming conventions!




More information about the Python-list mailing list