How python reads and writes Files
This article mainly introduces python how to read and write documents, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.
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 the file object file_object cannot execute the close () method when an exception occurs when opening the file. two。 Read file read text file input = open ('data', 'r') # the second parameter defaults to rinput = open (' data') read fixed bytes-file_object = open ('abinfile' 'rb') try: while True: chunk = file_object.read if not chunk: break do_something_with (chunk) finally: file_object.close () read each line list_of_all_the_lines = file_object.readlines () if the file is a text file You can also directly traverse the file object to get each line: for line in file_object: process line3. Write file write text file output = open ('data', 'w') write binary file output = open (' data', 'wb') append write file output = open (' data', 'wband') write data file_object = open ('thefile.txt', 'w') file_object.write (all_the_text) file_object.close () write multiline file _ object.writelines (list_of_text_strings)
Note that calling writelines to write to multiple lines has a higher performance than using write to write once. When dealing with log files, we often encounter such a situation: the log file is so large that it is impossible to read the whole file into memory at once for processing. For example, if we need to process a 2GB log file on a machine with physical memory of 2GB, we may want to process only the contents of 200MB in it at a time. In Python, the built-in File object directly provides a readlines (sizehint) function to do such a thing. Take the following code as an example: file=open ('test.log','r') sizehint=209715200#200Mposition=0lines=file.readlines (sizehint) whilenotfile.tell ()-position