Python Forum
open("python.pdf","wb") - why "wb" instead of "a"? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: open("python.pdf","wb") - why "wb" instead of "a"? (/thread-29176.html)



open("python.pdf","wb") - why "wb" instead of "a"? - Man_from_India - Aug-21-2020

I came across the following code in a website.

import requests 

file_url = "http://codex.cs.yale.edu/avi/db-book/db4/slide-dir/ch1-2.pdf"

  

r = requests.get(file_url, stream = True) 

  

with open("python.pdf","wb") as pdf: 

    for chunk in r.iter_content(chunk_size=1024): 

  

         # writing one chunk at a time to pdf file 

         if chunk: 

             pdf.write(chunk) 
Now the file is being written in chunks. So why it is opened as "w" (write mode), instead of "a" (append mode) because if we open the file as "w" we know that when the latest chunk will be written it will overwrite the file and we will loose the previous chunks.


RE: open("python.pdf","wb") - why "wb" instead of "a"? - Larz60+ - Aug-21-2020

'wb' -- will open a new file for writing, binary mode
'a' -- will open a new file, but if it already exists, will append to existing file.