1. After open is used to open a file, remember to call the close () method of the file object. For example, you can use the try/finally statement to ensure that the file can be closed at last.
File_object=Open ('Thefile.txt')
Try:
All_the_text=File_object.read ()
Finally:
File_object.close ()
Note: The open statement cannot be placed in the try block, because when an exception occurs when the file is opened, the file object file_object cannot execute the close () method.
2. Read a text fileInput=Open ('Data','R')
#The second parameter is r by default.
Input=Open ('Data')
Read Binary filesInput=Open ('Data','Rb')
Read all contentFile_object=Open ('Thefile.txt')
Try:
All_the_text=File_object.read ()
Finally:
File_object.close ()
Read fixed bytesFile_object=Open ('Abinfile','Rb')
Try:
WhileTrue:
Chunk=File_object.read (100)
If NotChunk:
Break
Do_something_with (chunk)
Finally:
File_object.close ()
Read each lineList_of_all_the_lines=File_object.readlines ()
If the file is a text file, you can directly traverse the file object to get each line:
ForLineInFile_object:
Process line
3. Write a file to write a text fileOutput=Open ('Data','W')
Write binary filesOutput=Open ('Data','Wb')
Append a fileOutput=Open ('Data','W +')
Write DataFile_object=Open ('Thefile.txt','W')
File_object.write (all_the_text)
File_object.close ()
Write multiple rowsFile_object.writelines (list_of_text_strings)
Note that calling writelines to write multiple rows has a higher performance than using write for one-time writing.