Detailed introduction to the Python open read/Write File implementation script

Source: Internet
Author: User

Script for reading and writing files in Python open

Remember to call the close () method of the object after opening the relevant file with open. For example, you can use the try/finally statement to ensure that the file can be closed. The following is a detailed introduction to the relevant content of the article. I hope you will gain some benefits.

 
 
  1. file_object = open('thefile.txt')  
  2. try:  
  3. all_the_text = file_object.read( )  
  4. finally:  
  5. 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.

Read files

Read text files

 
 
  1. input = open('data', 'r') 

The above code is used to implement the second parameter of the script in the Python open read/write file. The default value is r.

 
 
  1. input = open('data') 

Read Binary files

 
 
  1. input = open('data', 'rb') 

Read all content

 
 
  1. file_object = open('thefile.txt')  
  2. try:  
  3. all_the_text = file_object.read( )  
  4. finally:  
  5. file_object.close( ) 

Read fixed bytes

 
 
  1. file_object = open('abinfile', 'rb')  
  2. try:  
  3. while True:  
  4. chunk = file_object.read(100)  
  5. if not chunk:  
  6. break  
  7. do_something_with(chunk)  
  8. finally:  
  9. file_object.close( ) 

The above is an introduction to the content related to the Python open read/write file implementation script. I hope you will gain some benefits.

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.