Python Open Read-write file Implementation script _python

Source: Internet
Author: User

1.open

Always remember to call the close () method of the file object when you open the file with the. For example, you can use the Try/finally statement to ensure that the file is finally closed.

File_object = open (' thefile.txt ')
try:
  all_the_text = File_object.read ()
finally:
  file_ Object.close ()

Note: The Open statement cannot be placed in a try block because the close () method cannot be executed by the file object File_object when an exception is opened.

2. Read the document

Read a text file

input = open (' Data ', ' R ')
#第二个参数默认为r
input = open (' Data ')

Read binary files

input = open (' Data ', ' RB ')

Read all content

File_object = open (' thefile.txt ')
try:
  all_the_text = File_object.read ()
finally:
  file_ Object.close ()

Read fixed bytes

File_object = open (' Abinfile ', ' RB ')
try: While
  True:
    chunk = File_object.read (m)
    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 traverse the file object to get each line:

For line in File_object:
Process Line

3. Write a document

Write a text file
Output = open (' Data ', ' W ')

Write binary files
Output = open (' Data ', ' WB ')

Append Write file
Output = open (' Data ', ' w+ ')

Write Data

File_object = open (' Thefile.txt ', ' W ')
file_object.write (all_the_text)
file_object.close ()

Write Multiple lines
File_object.writelines (list_of_text_strings)

Note that calling Writelines writes to multiple lines is higher in performance than write-once writes.

Related Article

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.