Reading and writing text files in the python advanced tutorial,

Source: Internet
Author: User

Reading and writing text files in the python advanced tutorial,

Python has the basic function of reading and writing text files. The Python Standard Library provides richer read/write functions.

The read and write operations on text files are mainly implemented by file objects built by open.

Create a file object

Open a file and use an object to represent the file:
Copy codeThe Code is as follows:
F = open (file name, Mode)

 
The most common modes are:
Copy codeThe Code is as follows:
"R" # Read-Only
"W" # Write

For example
Copy codeThe Code is as follows:
>>> F = open ("test.txt", "r ")

File object Method

Read:
Copy codeThe Code is as follows:
Content = f. read (N) # read data of N bytes

Content = f. readline () # Read a row

Content = f. readlines () # Read all rows and store them in the list. Each element is a row.

Write:
Copy codeThe Code is as follows:
F. write ('I like apple') # write' I like apple' to a file

 
Close the file:
Copy codeThe Code is as follows:
F. close ()

Exercise

Create a record.txt file. The written content is as follows:

Tom, 12, 86
Lee, 15, 99
Lucy, 11, 58
Joseph, 19, 56
Then read and print the file from record.txt.

Summary

Copy codeThe Code is as follows:
F = open (name, "r ")
Line = f. readline ()
F. write ('abc ')
F. close ()




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.