Daily test
1,Three characteristics of elements in a set Must be of immutable type disorder No repetition 2,What is the purpose of the collection? Relational operation duplicate removal 3,An example is given to illustrate the relational operation intersection s1 & s2 Union s1 | s2 Difference set s1 - s2 s2 - s1 Symmetric difference set s1 ^ s2 Parent-child set Parent set: s1 >= s2 Established, i.e s1 contain s2,s1 yes s2 Parent set of subset s1 <= s2 Established, i.e s1 cover s2 contain, s1 yes s2 Subset of 4,List de duplication based on set l=[1,1,1,1,2,3,'a'] Briefly describe the limitations of set de duplication 1,There is no guarantee of the order of the objects being de duplicated l=list(set(l)) 2,All elements taken from the de duplicated object must be of immutable type set(l) 5,How to solve python2 Garbled code problem # Coding: consistent with the coding format of the file x=u"upper" 6,How to solve python3 Garbled code problem # Coding: consistent with the coding format of the file 7,code encode,decode decode x="upper" # str type = "is saved as unicode print(x) x.encode('gbk') 8,Supplement (understand) File header (just add a file header for the main file) #!/usr/bin/env python # -*- coding: utf-8 -*-
Introduction to file mode
1. What is a file
Files are provided to users by the operating system/A virtual concept in which applications operate hard disks/Interface user/application program(open()) Operating system (file) Computer hardware (hard disk)
2. Why use files
user/The application program can permanently save the data to the hard disk through files That is, operating the file is operating the hard disk user/Applications directly operate on files, and all operations on files are After sending the system call to the operating system, the operation will convert it into a specific hard disk operation
3. How to use file: open()
Control the mode of file reading and writing: t and b emphasize: t and b It cannot be used alone. It must be used with r/w/a Combined use t Text (default mode) 1,Both reading and writing are based on str(unicode)In units of 2,text file 3,Must specify encoding='utf-8' b Binary/bytes Controls the mode of file read and write operations r read only mode w Write only mode a Append write only mode +: r+,w+,a+
Basic operation flow of documents
1. Open file
windows Path separator problem open('C:\a.txt\nb\c\d.txt') Solution 1: Recommended r Cancel escape open(r'C:\a.txt\nb\c\d.txt') Solution 2 open('C:/a.txt/nb/c/d.txt') f = open(r'aaa/a.txt', mode='rt') # The value of f is a variable that takes up the memory space of the application print(f) # <_io.TextIOWrapper name='aaa/a.txt' mode='rt' encoding='cp936'>
2. Operation file
Read / write file, the application program's read / write request to the file is to send a system call to the operating system, and then the operating system controls the hard disk to read the input into the memory or write to the hard disk
res = f.read() print(type(res)) print(res)
3. Close file
f.close() # Reclaim operating system resources print(f) f.read() # Variable f exists but cannot be read any more del f # Reclaim application resources
with context manager
What is a context manager
This is a simple protocol (or interface). Custom objects need to follow this interface to support the with statement. In general, if you need to use an object as a context manager, all you need to do is add it__ enter__ And__ exit__ method. Python will call both methods at the appropriate time in the resource management cycle. For in-depth study of context manager, please refer to page 11 of the book "in-depth understanding of Python features". Only the key points are summarized here
1,with Statements are encapsulated in a so-called context manager try...finally Statement to simplify exception handling 2,with Statement is generally used to manage the secure acquisition and release of system resources. Resources are first determined by with Statement to get and leave after execution with Context auto release 3,Use effectively with It helps to avoid the problem of resource leakage and makes the code easier to read
Examples
with open('a.txt', mode='rt') as f1: # f1=open('a.txt',mode='rt') res = f1.read() print(res) with open('a.txt', mode='rt') as f1,\ open('b.txt', mode='rt') as f2: res1 = f1.read() res2 = f2.read() print(res1) print(res2) # f1. There is no need to write close() # f2.close()
Specify character encoding
''' emphasize: t and b It cannot be used alone. It must be used with r/w/a Combined use t Text (default mode) 1,Both reading and writing are based on str(unicode)In units of 2,text file 3,Must specify encoding='utf-8' ''' # If the encoding parameter is not specified, the operating system will use its own default encoding # linux system default utf-8 # windows system default gbk with open('c.txt', mode='rt', encoding='utf-8') as f: res = f.read() # t mode decodes the result read by f.read() into unicode print(res, type(res)) # Memory: utf-8 format binary ---- decoding ---- "unicode # Hard disk (c.txt content: binary in utf-8 format)
Detailed explanation of file operation mode (T mode)
Memory operation based on t mode
1. r (default operation mode)
In read-only mode, an error is reported when the file does not exist, and the file pointer jumps to the start position when the file exists
with open('c.txt', mode='rt', encoding='utf-8') as f: print('First reading'.center(50, '*')) res = f.read() # Read everything from hard disk to memory print(res) # with open('c.txt', mode='rt', encoding='utf-8') as f: print('Second reading'.center(50, '*')) res1 = f.read() print(res1)
case
inp_username = input('your name>>: ').strip() inp_password = input('your password>>: ').strip() # Verify account and password with open('user.txt', mode='rt', encoding='utf-8') as f: for line in f: # print(line,end='') # egon:123\n username, password = line.strip().split(':') if inp_username == username and inp_password == password: print('login successfull') break else: print('Wrong account or password') application program == ==>file application program == ==>Database management software == == =>file
w: Write only mode
When the file does not exist, an empty file will be created. When the file exists, the file will be emptied, and the pointer is at the start position
with open('d.txt', mode='wt', encoding='utf-8') as f: f.read() # Error reporting, unreadable f.write('Rub le\n') Emphasis 1: In order w When the file is opened in mode and not closed, the new content is always followed by the old one with open('d.txt', mode='wt', encoding='utf-8') as f: f.write('Rub le 1\n') f.write('Rub le 2\n') f.write('Rub le 3\n') Emphasis 2: If you re w If the file is opened in mode, the contents of the file will be emptied with open('d.txt', mode='wt', encoding='utf-8') as f: f.write('Rub le 1\n') with open('d.txt', mode='wt', encoding='utf-8') as f: f.write('Rub le 2\n') with open('d.txt', mode='wt', encoding='utf-8') as f: f.write('Rub le 3\n') Case: w Mode is used to create new files File file copy tool src_file = input('Source file path>>: ').strip() dst_file = input('Source file path>>: ').strip() with open(r'{}'.format(src_file), mode='rt', encoding='utf-8') as f1,\ open(r'{}'.format(dst_file), mode='wt', encoding='utf-8') as f2: res = f1.read() f2.write(res)
a: Append write only
An empty document will be created when the file does not exist, and the file pointer will be directly adjusted to the end when the file exists
with open('e.txt', mode='at', encoding='utf-8') as f: # f.read() # Error report, unable to read f.write('Wipe 1\n') f.write('Wipe 2\n') f.write('Wipe 3\n') emphasize w Mode and a Similarities and differences of modes: 1 The same point: when the open file is not closed, the newly written content will always follow the previously written content 2 Differences: in a Reopening the file in mode will not empty the contents of the original file, but will directly move the file pointer to the end of the file, and the newly written contents will always be written at the end
Case: mode a is used to write new contents based on the original file memory, such as logging and registration
# Registration function name = input('your name>>: ') pwd = input('your name>>: ') with open('db.txt', mode='at', encoding='utf-8') as f: f.write('{}:{}\n'.format(name, pwd))
Understand that: + cannot be used alone, but must cooperate with r, w and a
with open('g.txt', mode='rt+', encoding='utf-8') as f: # print(f.read()) f.write('China') with open('g.txt', mode='w+t', encoding='utf-8') as f: f.write('111\n') f.write('222\n') f.write('333\n') print('====>', f.read()) with open('g.txt', mode='a+t', encoding='utf-8') as f: print(f.read()) f.write('444\n') f.write('5555\n') print(f.read())
task
#1: Today's assignment: #1. Write file copy tool #2. Write the login program, and the account password comes from the file #3. Write the registration program, account and password to store the file #2: Weekend comprehensive operation: # 2.1: write user login interface #1. Enter the account and password to complete the verification, and then output "login succeeded" after passing the verification #2. You can log in to different users #3. Lock the same account for three times by mistake (prompt: the locked user is stored in the file, so as to ensure that the user is still locked after the program is closed) # 2.2: after the user is registered (registered in the file), the user can log in (the login information comes from the file) Tips: while True: msg = """ 0 sign out 1 Sign in 2 register """ print(msg) cmd = input('Please enter the command number>>: ').strip() if not cmd.isdigit(): print('You must enter the number of the command number, silly cross') continue if cmd == '0': break elif cmd == '1': # Login function code (additional: the previous loop can be nested and exit with three input errors) pass elif cmd == '2': # Registration function code pass else: print('The command you entered does not exist') # Think: will the functions of this if branch be implemented in other more graceful ways