Python Automation Development Learning 2-2

Source: Internet
Author: User

Collection

You can create a collection with Set (), or directly with {}

Set_a = Set ([1,2,3,4,5]) Set_b = {1,3,5,7,9}print (set_a) print (set_b) print (Type (set_a), type (set_b))

The collection also has a variety of operations, which can be recorded in several symbols. Check it out when you get to the other.

Set_a = Set ([1,2,3,4,5]) Set_b = {1,3,5,7,9}print (set_a | set_b) # and set print (Set_a & set_b) # intersection print (set_a ^ set_b) # Symmetric difference print (set_a-set_b) # difference set Print (set_b-set_a) # or differential

There is no "+" sign, and the set already has "|" The number can be obtained.

3 Methods in the collection delete:

Set_a = Set ([1,2,3,4,5]) Set_b = {1,3,5,7,9}c = Set_a.pop () # Randomly deletes one, the returned value is the deleted element print (C,SET_A) Set_b.remove (3) # Specifies to delete an element of PRI NT (Set_b) Set_b.discard (7) # is also specified to delete an element print (Set_b) Set_b.discard (2) # Discard allows an attempt to delete an element that does not exist, but remove will error #setb.discard ( 2) print (Set_b)

Operation of the file

Open () opens the file. Windows system defaults to GBK encoding, and if you do not specify a character encoding, the file is opened using the system's default character encoding. For example, Python will use GBK encoding to read the Utf-8 file, after the operation will be error or read garbled.

Our approach now is to use the UTF-8 encoding format for all files. When open, do not omit this parameter, directly specify the character encoding of Utf-8.

Basic operation of the file:

File = open (' Test.txt ', encoding= ' Utf-8 ') # Opens the files, specifying Utf-8data = File.read () # reads the entire contents of the file print (data) # Prints the Read content File.close () # Close File

Read the contents of a file to print on line:

File = open (' Test.txt ', encoding= ' Utf-8 ') # Opens the files, specifying Utf-8for line in File:print (Line.rstrip ()) # Plus Rstrip to remove the right side of each row Spaces (including newline characters) File.close ()

It is recommended that the above method be implemented. The method is to read one line at a time, let the post-operation, and then process the next line. This is an efficient approach .

If you are using an implementation that reads the entire file into memory and then processes it (such as ReadLines ()), it is much less efficient when working with large files. Although that also has to be large enough (up to now the level of memory capacity several G).

However, when this method is processed, the data is not a list, to get the line number, you can only add a counter at the start of the For loop, and then increment by 1 each time, to record the line number

File = open (' Test.txt ', encoding= ' Utf-8 ') # opens files, specified here Utf-8count = 0for line in File:count + = 1 print (count,line.rs Trip ()) # Add Rstrip to remove the space to the right of each line (including newline characters) File.close ()

Flush (): Force refresh. The default write to the file, is to write the cache first, and so on to a certain amount of memory and then write to the hard disk. If the real-time requirements of the data is high, and do not want to close the file, you need this method to manually force a write to the hard disk operation.

File = open (' Test.txt ', ' a ', encoding= ' Utf-8 ') # opens files, append mode File.write ("Back me up cache \ n") input ("Go to open file to see if the file is updated") File.flush ( Print ("Now open the file to see if there is an update") input ("The file will be written before closing, I have not tried again") File.write ("Try again, first cache me \ n") input ("Open file to see if the file has been updated") print (" Now open the file to see if there is an update ") File.close ()

Verify that the files on the hard disk are not updated in real time. But after flush () or close (), it's up to date to confirm the file.

Modification of files

File modification is troublesome, there is no way to make a direct modification. If you want to implement it, you can write it all over again.

Method One: Read the entire contents of the file one at a time, then modify, then write back. Not suitable for large files

File = open (' Test.txt ', encoding= ' utf-8 ') lines = File.readlines () # reads the source file File.close () File_w = open (' Test2.txt ', ' W ', encoding= ' Utf-8 ') # Reopen a file here for easy comparison, using a new filename #file_w = open (' Test.txt ', ' W ', encoding= ' Utf-8 ') # Use the original file name to open the write directly to implement the file modification for Count,line_w in enumerate (lines): if count+1 = = 3:line_w = "This is the third line to be replaced \ n" # Here to modify the replacement Three lines of content, don't forget \ nthe newline file_w.write (line_w) # writes content Zhuhang to a new file File_w.close ()

Method Two: You can also take a read line, write a line of the way. Avoid reading too much content at once, which is more suitable for scenarios where large files are used. Recommended:

File = open (' Test.txt ', encoding= ' Utf-8 ') # Opens the source file File_w = open (' Test2.txt ', ' W ', encoding= ' Utf-8 ') # New temporary new file count = 0 #    In this case, the number of rows can only be counted by the counter. For lines in File:count + = 1 if count = = 3:line = ' This is the third line to be replaced \ n ' # Change the contents of the third line here, and don't forget to change the line File_w.write (line) # writes content Zhuhang to a new file File.close () File_w.close ()

Did not complete the modification of the file, only to change the source file after the generation of a new file. You will also need to delete the source file and rename the new file. The operation of the file (not the file content), but also the need to call the OS module, but not difficult. And it's not the focus of the class, it's skipped.

Problem with file close

After the file is exhausted, you can close the file with close () and release the file handle. If not, the problem is small (but certainly not a good habit). In addition, all open files will be closed after the program has finished running.

In short, open the file and if you don't, you should close it.

Use with to open the file, you can automatically close the file (by indenting, after the code block executes, automatically close the file). So if the condition allows, try to open the file with a with. Rewrite the above 2 paragraphs with a.

# Note The indentation, through this to determine whether the file is finished, and thus automatically close with open (' Test.txt ', encoding= ' Utf-8 ') as File:lines = File.readlines () # Read the source file with Ope            N (' Test.txt ', ' W ', encoding= ' Utf-8 ') as File_w:for count,line_w in Enumerate (lines): if count+1 = = 3: Line_w = "This is the third line to be replaced \ n" # Here you change the contents of the third line, and don't forget to line up File_w.write (line_w) # write the content Zhuhang to the new file
# Multiple file contexts can be managed at the same time # In addition, a line of code is not recommended more than 80 characters, here super, so with a \ to branch # and line after the opening can be aligned Open, clearly show the number of opened files with the "Test.txt ', encoding= ' Utf-8 ') as file, open (' Test2.txt ', ' W ', encoding= ' Utf-8 ') as File_w:count = 0 # This situation can only be counted with a counter to calculate the number of rows in the for lines in Fil E:count + = 1 if count = 3:line = ' This is the third line that is replaced \ n ' # Change the contents of the third line here, and don't forget to line up File_w.write (li NE) # writes content Zhuhang to a new file

Homework

Shopping Cart Procedure:

1, after starting the program, enter the user name password, if it is the first time to log in, let the user enter wages, and then print the product list

2. Allow users to purchase goods according to the product number

3, the user selects the goods, checks whether the balance is enough, enough on the direct debit, not enough on the reminder

4, can withdraw at any time, exit, print purchased goods and balance

5, in the user process, the key output, such as the balance, the product has been added to the shopping cart and other messages, need to highlight

6, the user after the next login, enter the user name password, directly back to the last state, that is, the balance of the last consumption or those, re-login to continue to purchase

7, allow to query the previous consumption records

Above is the buyer's module, in addition to do a seller's module. After login, you can maintain the list of items, add, modify products and prices.




Python Automation Development Learning 2-2

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.