FILE HANDLING 2 BINARY FILES Writing in a

FILE HANDLING -2 BINARY FILES
![Writing in a Binary File f = open("file 1. dat", "wb") l=[101, 20, 30] Writing in a Binary File f = open("file 1. dat", "wb") l=[101, 20, 30]](http://slidetodoc.com/presentation_image_h2/85835cd2682d6d5d22cbb03f56b4b64d/image-2.jpg)
Writing in a Binary File f = open("file 1. dat", "wb") l=[101, 20, 30] f. write(l) f. close() >>> RESTART: C: UsersserverApp. DataLocalProgramsPython 37 -32write. py Traceback (most recent call last): File "C: UsersserverApp. DataLocalProgramsPython 37 -32write. py", line 4, in <module> f. write(l) Type. Error: a bytes-like object is required, not 'list' >>>

Writing in a Binary File Import pickle f = open("file 1. dat", "wb") l=[101, 20, 30] f. write(l) pickle. dump(l, f) f. close()

PICKLE MODULE Pickling refers to the process of converting the structure to a byte stream before writing to the file. While reading the content of the file, a reverse process called Unpickling is used to convert the byte stream back to the original structure

Reading from a Binary File Import pickle f = open("file 1. dat", “rb") list=pickle. load(f) Print(list) f. close()

File Object Mode: Once a file is opened and you have one file object, you can get various information related to that file f = open(“file. txt", "wb") print ("Name of the file: ", f. name) Print( "Closed or not : ", f. closed) print ("Opening mode : ", f. mode) This produces the following result − Name of the file: file. txt Closed or not : False Opening mode : wb

Delete a File To delete a file, you must import the OS module, and run its os. remove() function: Example Remove the file "demofile. txt": import os os. remove("demofile. txt")

Check if File exist: To avoid getting an error, you might want to check if the file exists before you try to delete it: Example Check if file exists, then delete it: import os if (os. path. exists("demofile. txt")): os. remove("demofile. txt") else: print("The file does not exist")

Delete Folder To delete an entire folder, use the os. rmdir() method: Example To Remove the folder "myfolder": import os os. rmdir("myfolder")
- Slides: 9