Python Learning note Nine-file read and write

Source: Internet
Author: User

1. Read the file:

F=open (' directory ', ' Read and write mode ', encoding= ' gbk,error= ' Egiong ') can not be written after three entries but the default is ' R ' read mode; The file object opened by the Open function is automatically added with the read () method;

F.read () read out the file you just opened; Finally, remember the close () function; otherwise there will be unpredictable consequences.

Read/write mode: R read-only, r+ read/write, W New (overwrites the original file), a append, b binary. Common mode. such as: ' RB ', ' WB ', ' r+b ' and so on

The ReadLine () function, which reads multiple file contents sequentially, returns a list by row. When reading, use an iteration to print(line.strip()# remove the/N of each line

With open (' Nihaoa.txt ') as F: easy to throw with try finally exception

For I in F.readlines ():

Print (I.strip ())

2, Write file:

Open the file first, and then use the Write method, in order to prevent the absence of close () or with

With open (' Nihaoa.txt ', ' W ') as F:

F.write (' Woshidahaoren ')

Note that the Write method overwrites the original file content directly;

Python Learning note Nine-file read and write

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.