"Python study notes" Coursera's py4e study notes--file

Source: Internet
Author: User

1. Open File

Use Handle=open (Filename,mode) to open the file. This function will return a handle (which should be translated as "handle") to manipulate the file, and the parameter filename is a string. The parameter mode is optional, ' R ' stands for reading the file, ' W ' represents the Write file.

Cases:

>>> Fhand=open ('mbox.txt','r')
>>> Print (Fhand)
<_io. Textiowrapper name= ' mbox.txt ' mode= ' r ' encoding= ' UTF-8 ' >

The file handle can be thought of as a sequence of strings, and each line of an instance of the document is the contents of the string sequence.

Example: Number of rows of file contents

Fhand=open ('mbox.txt') Count=0 for in Fhand:    count=count+1print('linecount:', count) $ python Open.pyline Count:132045

Example: Retrieving the contents of a file

Fhand = open (; mbox-short.txt') for in fhand:    if Line.startswith ('from:'):        print(line)

2. Read the file

Use Read () to read the entire file (including line breaks, etc.) and deposit a separate string.

Cases:

>>> Fhand=open ('mbox-short.txt')>>> inp=fhand.read ()  Print(len (INP))print(inp[:20]) from Stephen.marquar

"Python study notes" Coursera's py4e study notes--file

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.