Binary File in Python

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

Program 1

#Program for Binary Mode
#Program to copy one text file to other
import os
# try:
#     f1=open("d://filedata\student.txt","r")
#     f2=open("d://indore\student1.txt","w")
#     if(f1.readable() and f2.writable()):
#         mylist=f1.readlines()
#         f2.writelines(mylist)
#         print("file copied successfully")
#     else:
#         print("Invalid file")        
# except Exception as obj:
#     print(obj)            
# finally:
#     f1.close()
#     f2.close()    

#Program to copy one image file to other    
try:
    f1=open("d://filedata\dataflair.jpg","rb")
    f2=open("d://indore\data.jpg","wb")
    if(f1.readable() and f2.writable()):
        bytes=f1.read()
        print(bytes)
        f2.write(bytes)
        print("file copied successfully")
    else:
        print("Invalid file")        
except Exception as obj:
    print(obj)            
finally:
    f1.close()
    f2.close()

 

Did we exceed your expectations?
If Yes, share your valuable feedback on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *