Site icon DataFlair

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()

 

Exit mobile version