Converting text file to different encoding.
subhabrata.banerji at gmail.com
subhabrata.banerji at gmail.com
Fri Apr 17 10:26:57 EDT 2015
On Friday, April 17, 2015 at 7:36:46 PM UTC+5:30, Oscar Benjamin wrote:
> wrote:
> > On Friday, April 17, 2015 at 6:50:08 PM UTC+5:30, 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
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?
More information about the Python-list
mailing list