“This is the sixth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

Part one: : StringIO and BytesIO

True file: file contents are not lost when a file is closed. Fake file: Contents of a file are lost when the file is closed.

(1) StringIO:

StringIO literally reads and writes STR in memory. To write STR to StringIO, we need to create a StringIO and write it like a file:

Import IO # create IO Sio = io.stringio () sio.write(' study hard ') # print(sio.getValue ()) # Print (sio.getValue ()) # print(sio.getValue ()) # print(sio.getValue ()) # print(sio.getValue ()) # When the StringIO created calls close(), the # data in memory is lostCopy the code

(2) BytesIO stream:

StringIO can only operate on STR. If you want to operate on binary data, you need to use BytesIO. BytesIO implements reading and writing bytes in memory. We create a BytesIO and then write bytes!

BytesIO is similar to StringIO, but BytesIO operates on Bytes and decode decodes

Import IO bio = io.bytesio () bio. Write (b' hsfDHdsf124 ') B print(bio. Getvalue ()) bio. Write (' encode '.encode()) Print (bio. Getvalue (). Decode ()) print(bioCopy the code

Note: Call the close() method to save the data in memory and ensure that the data in memory is not lost. Prevent the occupation of a resource. If it is not closed, then the IO resource will be occupied by it, and other people want to use it.

Part two: : Context management with……. as

What it does: Makes Python perform the closing process automatically, calling the close() method. Manage multiple files automatically close.

First, when operating on a single file:

With open(file_path, mode='r') as f: open(file_path, mode='r') as fCopy the code

Auto-execute f.close() when jumping out of with statement fast

Then, for multiple file operations:

with open(file_path, mode='r') as f1,\ open(file_path, mode='r') as f2,\ . . . open(file_path, mode='r') as fn: File. Closed To see if the file is closedCopy the code

Automatically execute f.close() when exiting the with block

Finally, two underlying methods: enter__ and __exit

class Person:
    def __enter__(self):                        # 进入的时候自动调用
        print('this is enter')
        return '吴某好帅'


    def __exit__(self,exc_type,exc_val,exc_tb):    #退出的时候自动调用
        print("this is exit")
Copy the code

#with allows you to open classes and manage multiple methods

A = Person() with as f: #with Print (f) #f is the return value of __enter__Copy the code

When finished, the __exit__ method is automatically called

The output is: This is enter 111 This is exit