Python Advanced 02 text file input and output

Source: Internet
Author: User

Python has basic text file reading and writing capabilities, and Python's standard library provides richer read and write capabilities.

Text files are read and written primarily through the file object built by open () to achieve

To create a file object

We open a file and apply an object to represent the file:

f = open (file name, mode)

The most commonly used patterns are:

"R" # read-only

"W" # Write

Like what

>>>f = open ("Test.txt", "R")

Methods for File objects

Read:

Content = F.read (n) # reads N bytes of data

Content = F.readline () # reads a line

Content = F.readlines () # reads all rows, is stored in the list, and each element is a row.

Write:

F.write (' I like Apple ') # write ' I like Apple ' to file

To close a file:

F.close ()

Practice

Create a Record.txt document and write the following:

Tom, 12, 86

Lee, 15, 99

Then read the file from the Record.txt and print it.

Summarize

f = open (name, "R")

line = F.readline ()

F.write (' abc ')

F.close ()

Python Advanced 02 text file input and output

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.