Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #89071

Re: Converting text file to different encoding.

References <6bddf2c0-b0c3-456d-a699-d6c921e6fc73@googlegroups.com> <d921df37-c353-4e3b-8948-12ef05eb2870@googlegroups.com> <mailman.367.1429279585.12925.python-list@python.org> <99b92c62-6fe0-4752-b64c-bff909faa6b8@googlegroups.com>
Date 2015-04-18 00:41 +1000
Subject Re: Converting text file to different encoding.
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.370.1429281718.12925.python-list@python.org> (permalink)

Show all headers | View raw


On Sat, Apr 18, 2015 at 12:26 AM,  <subhabrata.banerji@gmail.com> wrote:
> I tried to do as follows,
>>>> import codecs
>>>> sourceEncoding = "iso-8859-1"
>>>> targetEncoding = "utf-8"
>>>> source = open("source1","w")
>>>> string1="String type"
>>>> str1=str(string1)
>>>> source.write(str1)
>>>> source.close()
>>>> target = open("target", "w")
>>>> source=open("source1","r")
>>>> target.write(unicode(source.read(), sourceEncoding).encode(targetEncoding))
>>>>
>
> am I going ok?

Here's how I'd do it.

$ python3
>>> with open("source1", encoding="iso-8859-1") as source, open("target", "w", encoding="utf-8") as target:
...     target.write(source.read())

Or maybe this:

$ pike
> Stdio.write_file("target", string_to_utf8(Stdio.read_file("source1")));

So much easier than fiddling around with all those steps you're doing.
I'm not sure what they're all for, anyway; calling str() on a
double-quoted literal isn't usually going to do anything, and I don't
see "from __future__ import unicode_literals" anywhere.

ChrisA

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


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