Py3 - converting bytes to ascii

  • Thread starter Anjanesh Lekshminarayanan
  • Start date
A

Anjanesh Lekshminarayanan

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.

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

Thanks
 
C

Casey

Using Python 3.0

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

I think this is what you are looking for:

res = urllib.request.urlopen(url)
f = open('file.txt', 'w')
f.write(res.read().decode('ascii'))
 
J

John Machin

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
 
A

Anjanesh Lekshminarayanan

The problem seems be solved with urllib.request.urlretrieve()
I think the binary information read() was giving had headers like
content-size - but not HTTP headers.
The first couple of bytes indicate how much content to read and after
reading that content, the next set of bytes indicate the next chunk.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,021
Latest member
AkilahJaim

Latest Threads

Top