Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #89067
| References | <6bddf2c0-b0c3-456d-a699-d6c921e6fc73@googlegroups.com> <d921df37-c353-4e3b-8948-12ef05eb2870@googlegroups.com> |
|---|---|
| From | Oscar Benjamin <oscar.j.benjamin@gmail.com> |
| Date | 2015-04-17 15:05 +0100 |
| Subject | Re: Converting text file to different encoding. |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.367.1429279585.12925.python-list@python.org> (permalink) |
On 17 April 2015 at 14:51, <subhabrata.banerji@gmail.com> wrote:
> On Friday, April 17, 2015 at 6:50:08 PM UTC+5:30, subhabrat...@gmail.com wrote:
>> I am having few files in default encoding. I wanted to change their encodings,
>> preferably in "UTF-8", or may be from one encoding to any other encoding.
>>
>> I was trying it as follows,
>>
>> >>> import codecs
>> >>> sourceEncoding = "iso-8859-1"
>> >>> targetEncoding = "utf-8"
>> >>> source = open("source1","w")
>> >>> target = open("target", "w")
>> >>> target.write(unicode(source, sourceEncoding).encode(targetEncoding))
>>
>> but it was giving me error as follows,
>> Traceback (most recent call last):
>> File "<pyshell#6>", line 1, in <module>
>> target.write(unicode(source, sourceEncoding).encode(targetEncoding))
>> TypeError: coercing to Unicode: need string or buffer, file found
The error comes from `unicode(source, sourceEncoding)` and results
from the fact that source is a file object when it should be a string.
To read the contents of the file as a string just change `source` to
`source.read()`.
Oscar
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Converting text file to different encoding. subhabrata.banerji@gmail.com - 2015-04-17 06:19 -0700
Re: Converting text file to different encoding. Rustom Mody <rustompmody@gmail.com> - 2015-04-17 06:31 -0700
Re: Converting text file to different encoding. subhabrata.banerji@gmail.com - 2015-04-17 06:51 -0700
Re: Converting text file to different encoding. Oscar Benjamin <oscar.j.benjamin@gmail.com> - 2015-04-17 15:05 +0100
Re: Converting text file to different encoding. subhabrata.banerji@gmail.com - 2015-04-17 07:26 -0700
Re: Converting text file to different encoding. Chris Angelico <rosuav@gmail.com> - 2015-04-18 00:41 +1000
Re: Converting text file to different encoding. Marko Rauhamaa <marko@pacujo.net> - 2015-04-17 17:51 +0300
Re: Converting text file to different encoding. Peter Otten <__peter__@web.de> - 2015-04-17 17:06 +0200
Re: Converting text file to different encoding. Dave Angel <davea@davea.name> - 2015-04-17 10:48 -0400
Re: Converting text file to different encoding. Dave Angel <d@davea.name> - 2015-04-17 10:57 -0400
csiph-web