In your first block, open file in binary write mode (wb), since you are writing binary to it. Also, you don't need to convert it explicitly to str. It should look like this:
file = open('code.txt', 'wb')
for line in open('somefile.pdf', 'rb').readlines():
file.write(line)
file.close()
For second block, open file in read binary mode (rb). Here also, no need to explicitly convert to bytes. It should look like this:
file = open('new.pdf', 'wb')
for line in open('code.txt', 'rb').readlines():
file.write(line)
file.close()
This should do the trick. But why do you need to convert it in the first place? Keeping file intact will save your hardwork and computational power.
Answer from Jay Bhavsar on Stack OverflowIn your first block, open file in binary write mode (wb), since you are writing binary to it. Also, you don't need to convert it explicitly to str. It should look like this:
file = open('code.txt', 'wb')
for line in open('somefile.pdf', 'rb').readlines():
file.write(line)
file.close()
For second block, open file in read binary mode (rb). Here also, no need to explicitly convert to bytes. It should look like this:
file = open('new.pdf', 'wb')
for line in open('code.txt', 'rb').readlines():
file.write(line)
file.close()
This should do the trick. But why do you need to convert it in the first place? Keeping file intact will save your hardwork and computational power.
Just to add. In my case, I was downloading the pdf file from an API and the 'response.content' came in base64 format. I also didn't need to write line by line I needed to convert the byte array first using:
import requests
import base64
response = requests.get(self.download_url,
allow_redirects=True,
headers=headers,
params=query_params)
bytes = base64.b64decode(response.content)
with open('file.pdf', 'wb') as f:
f.write(bytes)