Python study notes 9-file read/write,

Source: Internet
Author: User

Python study notes 9-file read/write,

1. Read files:

F = open ('directory', 'read/Write mode', encoding = 'gbk, error = 'egiong '). The last three items can be left blank, but the default value is 'R; the read () method is automatically added to the file object opened by the open function;

F. read () read the file you just opened. Remember to close () the function at last; otherwise, unpredictable consequences may occur.

Read/write mode: r read-only, r + read/write, w new (will overwrite the original file), a append, B binary file. Common Mode. For example, 'rb', 'wb ', 'r + B', etc.

The readline () function reads multiple files in turn and returns the list by row. An iteration is used for reading,Print (line. strip ()#Remove/n from each line

With open('nihaoa.txt ') as f: facilitates the way to throw exceptions in try finally.

For I in f. readlines ():

Print (I. strip ())

2. Write files:

Open the file first, and then use the write method. To prevent the use of

With open('nihaoa.txt ', 'w') as f:

F. write ('woshidahaoren ')

Note that the write method will directly overwrite the original file content;

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.