Python learning note 5:python Read and write files

Source: Internet
Author: User

Python learning note 5:python Read and write files

First, the open mode of the file

  1. Open File

1) f=open (' D:\\a.txt ', ' W ')

The first parameter is the path to the file, and if only the name of the file is written, the default is the file under the current execution directory, and the second parameter is the open mode of the file.

This way to open the file, after the use of it must remember, close the file: F.close ()

2) with open (' D:\\a.txt ', ' W ') as F

This way the file is opened and the file is automatically closed after it is used, no close is required

 2. Open mode of File

In general, there are three types of open files: Read, write, append

This is derived from the following:

    

Ii. methods of reading and writing files

  

III. Traversal of files

Looping is the contents of each line of the file

  

Iv. Modifying the contents of a file-using 2 files

Scene:

There is a file with content written inside it, now modify the contents of the file, and then save it.

Ideas:

Open the file, use the loop method, read a line, modify/not modify the contents of this line, and then write the new file inside; Finally, delete the old file and name the new file the same as the original name.

  

  Scenario Instantiation: D disk has a file a.txt, its content is like, now the file of all 12 changed to 00

  Code implementation: (After the modification, D disk only one file a.txt, content such as two)

    

  

Python learning note 5:python Read and write files

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.