Py3 - converting bytes to ascii

John Machin sjmachin at lexicon.net
Thu Jan 15 17:13:12 EST 2009


On Jan 16, 1:54 am, "Anjanesh Lekshminarayanan" <m... at anjanesh.net>
wrote:
> Using Python 3.0
>
> res = urllib.request.urlopen(url)
> f = open('file.txt', 'wb') # Since res.read() returns bytes
> f.write(res.read())
>
> But newline and return feeds are stored as b14, 58a as text in the text file.

I can't imagine how a newline (aka line feed) and/or a carriage return
could end up being stored as "b14, 58a as text in the text file". What
are you using to view the output file?

Before you start trying to fix the problem, we need to understand it.
You can use Python itself to show you exactly what is in the file, in
a format that you can copy and paste into a news posting.

f = open('file.txt', 'rb')
data = f.read()
f.close()
print(ascii(data)) # Python 3.x
# print repr(data) # Python 2.x

> So how do I to convert res.read() to ascii on opening the file in
> ascii mode f = open('file.txt', 'w')?

Are you as sure as Casey is that your data is ASCII-only? Or are you
using "ascii" to mean "text" or "not binary"? Let's see your data
first.

Perhaps if you could give us a few clues like how much experience you
have in (Python 3.0, Python 2.x, using urllib, computer programming in
general) we could give you somewhat more focussed advice.

HTH,
John



More information about the Python-list mailing list