Python Open Read-write file Implementation script code display

Source: Internet
Author: User
The file operation in Python can be done through the open function, which is really like the fopen in the C language. Use the Open function to get a file object, and then call Read (), write (), and so on to read and write the files.

1.open

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

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 is opened to the file.

2. Read the file

Read text file

input = open (' Data ', ' r ') #第二个参数默认为rinput = 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 byte

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 traverse the file object directly to get each line:

For line in File_object:    process Line

3. Writing files

Write a text file

Output = open (' Data ', ' W ')

Write a binary file

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 multiple rows at a higher performance than using write one-time writes.

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.