Python Advanced Learning (i)

Source: Internet
Author: User
Tags pprint

The same is the "Basic Python Tutorial (second edition)" content, but the later content to learn, compared to the previous will be more interesting, but also more practical, so the "base" to "advanced."

Python ebook sharing address: http://yunpan.cn/Q2U87uGrNiTA3

This section speaks about the operation of the file

-------------------------------

Open File

The Open function is used for opening the file with the following syntax:

Open (name[, mode[,buffering])

The Open function uses a file name as the only mandatory argument, and then returns one of the document objects. Suppose I want to open my hard drive (i:/python/test.txt) file, you can use the following method:

>>> f = open (R'i:\python\test.txt')  

common values for modal parameters in the Open function

Basic File Method

Opening a file is the first step, you need to read or write the file below, and you can read or write the write and read methods.

#Write file contents >>> F = open (‘Test.txt‘,‘W‘) >>> F.write (‘Hello‘) >>> F.write (‘world!  ' ) >>> F.close () # Read file contents >>> f = open (  "test.txt",  ' r ) > >> F.read (4) # Read the first 4 characters  "hell" >>> F.read () # Read all remaining characters o,world!  "             

Close File

You should remember to close the file using the close method. Although a file object shuts down automatically after exiting the program, it is harmless to close the file, avoiding unwanted modifications in some operating systems or settings, and avoiding the quota of open files on the system.

Using the basic file method

If the Test.txt file contains the following content:

-----------------------------

Welcome to this file

There is nothing here except

This stupid haiku

-----------------------------

Here's how to read a basic file:

#Read (n) specify parameters >>> F = open (r‘I:\python\test.txt‘) >>> F.read (7)‘Welcome' >>> F.read (4)‘To' >>>F.close ()#Read () does not specify parameters >>> F = open (r‘I:\python\test.txt‘) >>>PrintF.read () Welcome to this FilethereIs nothing hereExceptThis stupid haiku>>>F.close ()#ReadLine () >>> f = open (r‘I:\python\test.txt‘) >>>For IIn range (3):Print str (i) +‘:' +F.readline () 0:welcome to this File1:thereIs nothing hereExcept2:this stupid haiku>>> F.close () #readlines () >>> import pprint>>> pprint.pprint (open (R ' i:\python\test.txt ' ). ReadLines ()) [ ' welcome to this file\n  ' there is nothing here Except\n ' this stupid haiku "      

ReadLine Returns a row of strings , ReadLines Returns a list of strings containing all the contents of the file, each of which is a string of one line.

the Pprint method of the Pprint module divides the content into a single line display of each small item.

Here is the basic way to write a file:

>>> f = open (R'I:\python\test.txt','w# default is read file, can not add ' r ', write file must add ' W ' >>> F.write ('this\nis no \nhaiku') >>> f.close ()        

>>> f = open (R'I:\python\test.txt') >>> lines ="isn ' t a\n" >>> F = Open (R'I:\python\test.txt','w') >>> f.writelines (lines) >> > f.close ()              

Iterate over the contents of a file

1, byte processing

The most common way to iterate over the contents of a file is to use the Read method in a while loop . For example, looping through each character can be done in the following way:

f = open (filename) char = f.read (1)while char:    process (char)    char = f.read (1) F.close ( )

the string returned by the Read method contains a character until the end of the file,read returns an empty string, andchar becomes false.

As you can see, char = F.read (1) is used repeatedly, code repetition passes is considered a bad thing, look at the following method:

f = open (filename)while True:    char = f.read (1) break     process (char) f.close () 

Here the break statement is used frequently (which makes the code difficult to understand), but it is still better than the previous method.

2. Read all content

If the file is not very large, you can use the Read method without parameters to read the entire file at once, or use the readlines method.

# with read iterate each character F = open (filename) in f.read (): Process (char) f.close ()
# Iterate lines with readlines: F = open (filename) in f.readlines (): Process (line) F.close ()

3. Use fileinput to iterate

The Fileinput module contains the function to open the file, and it only needs to pass a file name to it

Import fileinputin fileinput.input (filename):    process (line)  

4. File iterator

All right! This is the method after the python2.2, if it is in the beginning, the above method may not exist. File objects can be iterated, which means that they can be iterated directly in the For loop

f = open (filename)in F:    process (line) F.close ()  

Take another look at the following example:

>>> f = Open (r‘I:\python\test.txt‘,‘W‘) >>> F.write (‘First line\n‘) >>> F.write (‘Second line\n‘) >>> F.write (‘Third line\n‘) >>>F.close () >>> lines = List (open (R‘I:\python\test.txt‘)) >>>lines[‘First line\n‘,‘second line\n ",  third line\n "]>>> first , Second,third = open (Ri:\python\test.txt ' ) >>> First ' first line\n ' >>> Second" second line\n  ' >>> Thirdthird line\n "      

In this example:

    • using a sequence to unpack an open file, putting each line in a separate variable, is useful because it is generally not known how many lines are in the file, but it demonstrates the "iterative" nature of the file.
    • Be sure to close the file after writing it so that the data is updated to the hard disk.

Python Advanced Learning (i)

Related Article

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.