Python notes • Chapter seventh--io (file) processing

Source: Internet
Author: User

I. Introduction to the processing of documents

The computer system is divided into three parts: the hardware, the operating system and the application.

Applications that we write in Python or other languages need to be saved on the hard drive if we want to keep the data permanently, which involves the application operating hardware, and it is well known that the application is not able to manipulate the hardware directly. The operating system encapsulates complex hardware operations into a simple interface for use by the user/application, where the file is the operating system provided to the application to manipulate the virtual concept of the hard disk, and the user or application can save its own data permanently by manipulating the file.

With the concept of a file, we no longer have to consider the details of the operation of the hard disk, just the process of manipulating the files:

# 1. Open the file, get the file handle and assign the value to a variable #2. Manipulating files by handle #3. Close File
Second, the method of opening the file

①f = open (' filename ', ' operation mode ', ' encoded format ') such as:

f = open ('test.txt','r', encoding='utf-8 ')

Note: Open the file in this way and be sure to call the F.close () method to close it when you're done with it

②with open (' filename ', ' operation mode ', ' encoded format ') as F if:

With open ('day8.txt','w', encoding='  utf-8') as F:

Note: Opening the file in this way will automatically close the file after processing, but the processed paragraph will be indented

Iii. Several modes of operation files

Iv. Several methods of processing documents

The sample files are as follows:

Read the file:

Read ()

Read the entire file

1 with open ('love.txt','r', encoding=' Utf-8 ' ) as F:2     msg = ()3     print(msg)

Read (int)

The read () method can specify the number of characters to read, note that it is the number of characters, not the number of bytes, as follows:

1 with open ('love.txt','r', encoding=' Utf-8 ' ) as F:2     msg = ()3     print(msg)
#结果为 ' life '

ReadLine ()

A row can be read as follows:

1 with open ('love.txt','r', encoding=' Utf-8 ' ) as F:2     msg = f.readline ()3     print(msg)
#结果是 ' Love of the life '

ReadLines ()

You can read the entire article and add each row as an element to a list, as follows:

With open ('love.txt','r', encoding='utf-8  ') as f:    = f.readlines ()    print(msg)#  ' The    abyss of Love and Hate ', ' in the world is difficult to escape fate \ ', ' Blind Date is not close to \ \ ' Or I should believe it is fate ']     

For Lin in F:

Each row can be read directly in a circular way. F is an object that can be iterated

1With open ('Love.txt','R', encoding='Utf-8') as F:2      forLineinchF:3         Print(line,end="')4 #The result is:5 #the love of my Life6 #singing: Luguanting7 #Once Upon a time , no more.8 #red and red leaves buried in the dust9 #The beginning of the end is always unchanged .Ten #on the horizon you float outside the clouds One #The abyss of Love and Hate A #It 's hard to avoid fate in the world - #The Blind Date is not close - #or I should believe it's fate

Write file:

Write (str)

You can specify the write mode, if the file does not exist, re-create one, if it already exists, W mode will overwrite the previous text, re-write, a mode is appended at the end.

1 with open ('love.txt','w', encoding=' Utf-8 ' As f:2     f.write (' This passage will cover the previous article ')

3 with open (' Love.txt ', ' a ', encoding= ' utf-8 ') as F:
4 f.write (' This passage will not overwrite the previous article ')

The movement of the cursor

Seek ()

The syntax is: FileObject.  Seek(offset, whence)      
    • Offset--the beginning of the offsets, that is, the number of bytes required to move the offset, Note that is the number of bytes, negative numbers are represented as before moving

    • whence: optional, default value is 0. Give the offset parameter a definition of where to start the offset, and 0 to start at the beginning of the file, 1 to start at the current position, and 2 for the end of the file.

 1  with open ( " love.txt  , "  r   ", Encoding="   Utf-8   " ) as F:  2  print  ( (3)) #   read 3 characters: Lifetime  3 (3) #   The cursor moves backwards from the starting point by 3 bytes (1 Chinese)  4  print  ( (3)) #   and start reading from the previous base: Live Love  

Tell ()

Can get the current cursor position, return the number of bytes

Intercepting files

Truncate ()

This method is to intercept the file, note that the original file is directly intercepted. The parameter is to fill in a byte number, as follows:

1 with open ('love.txt','r+', encoding='  utf-8') as F:2     f.truncate (9) #截取9个字节, is 3 Chinese 3     Print ( ()) #再读取的内容结果为:  3 words in a lifetime

Five: After-school exercises (registration, login small system)
1 #user registration, the user name and password exist in the file, and then verify the login information, give 3 chance2 Print('************* Registration Information *************')3  while1:4Username = input ('Please enter your user name:'). Strip ()5Password ="'6Password1 = input ('Please enter your registration password:'). Strip ()7Password2 = input ('Please enter your registration password again:'). Strip ()8     ifPassword1 = =Password2:9         Print('Congratulations, your registration is successful! ')TenPassword =Password1 One          Break A     Else: -         Print('you entered the password two times different, please re-enter! ') -With open ('Day8.txt','W', encoding='Utf-8') as F1: the  -     #F1.write (' {%s:%s} '% (Username,password)) -F1.write ('%s:%s'%(Username,password)) -  + Print('************* Login Information *************') -  +Count = 3 AWith open ('Day8.txt','R', encoding='Utf-8') as F2: atUser_list = (). Split (':') -  -     #print (user_list) -      whileCount >0: -Username = input ('Please enter your user name:'). Strip () -Password = input ('Please enter your password:'). Strip () in         ifUsername = = User_list[0] andPassword = = User_list[1]: -             Print('Congratulations, the landing is successful! ') to              Break +         Else: -Count-= 1 the             Print('Login failed, please re-enter! You also have%s chance'%count)

Python notes • Chapter seventh--io (file) processing

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: 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.