Python3 common file reading Method Instance analysis,
This document describes how to use Python3 to read files. Share it with you for your reference. The details are as follows:
''' Created on Dec 17,201 2 read the file @ author: liury_lab ''' # the most convenient way is to read all the content of the file in a large string at a time: all_the_text = open ('d:/text.txt '). read () print (all_the_text) all_the_data = open ('d:/data.txt ', 'rb '). read () print (all_the_data) # more standard method file_object = open ('d:/text.txt ') try: all_the_text = file_object.read () print (all_the_text) finally: file_object.close () # '\ n' file_object = open ('d:/text.txt') try: all_the_text = file_object.readlines () print (all_the_text) finally: file_object.close () # Remove '\ n' from the end of all three sentences. file_object = open ('d:/text.txt') try: # all_the_text = file_object.read (). splitlines () # all_the_text = file_object.read (). split ('\ n') all_the_text = [L. rstrip ('\ n') for L in file_object] print (all_the_text) finally: file_object.close () # Read file_object row by row = open ('d:/text.txt') try: for line in file_object: print (line, end = '') finally: file_object.close () # def read_file_by_chunks (file_name, chunk_size = 100 ): file_object = open (file_name, 'rb') while True: chunk = file_object.read (chunk_size) if not chunk: break yield chunk file_object.close () for chunk in read_file_by_chunks ('d: /data.txt ', 4): print (chunk)
The output is as follows:
hello pythonhello worldb'ABCDEFG\r\nHELLO\r\nhello'hello pythonhello world['hello python\n', 'hello world']['hello python', 'hello world']hello pythonhello worldb'ABCD'b'EFG\r'b'\nHEL'b'LO\r\n'b'hell'b'o'
I hope this article will help you with Python programming.