Python3 common file reading Method Instance analysis,

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.