Login registration function exercise optimization, cursor movement in the file, file data modification, function introduction, other methods of file operation read-write mode

Complementary knowledge

1.r+'File path'Function: to cancel the special meaning of crowbar and letter combination
2.After inputting a string, users often assign a value to a variable name. When operating on the variable name, placeholders are often used if they want to add characters to the string or cancel escape(%s),Format output(.format)
3.Try not to modify the number of data values in the data type when circulating the data type
  eg:
    l1 = [1,2,3,4,5,6,7,8]
    for i in l1:
        l1.pop()
        print(i)  # i value 1, 2, 3, 4
    print(l1)  # [1, 2, 3, 4]
  ps:This is not allowed

Job optimization

1. Write a simple version of the copy tool
Enter the data path you want to copy. Enter the target path to which you want to copy
Any type of data can be copied
ps: the files on the C disk of some computers may not be copied due to permission problems. Try to change to another disk

resource_path = input("Please enter the path where you want to copy the file>>>:").strip()
target_path = input("Please enter the destination path of the file you copied>>>:").strip()
with open(r'%s' % resource_path, 'rb')as f1, open(r'%s'%target_path,'wb')as f2:
    for line in f1:
        f2.write(line)

2. Use files as the database to write user login and registration functions
File name: userinfo txt
1. basic requirements:
User registration function > > >: add user data (user name, password, etc.) to the file
User login function > > >: read the user data in the file for verification
ps: the above functions only need to be implemented once, even if there is always one user information in the clearance (single user) file

1.Single user registration function
real_name = input("Please enter the user name you want to register>>>:").strip()
with open(r'userinfo.txt','r',encoding='utf8') as f1:
    data = f1.read()
    data1=data.split('|')[0]
    if data1 ==real_name:
        print("User name already exists")
    else:
        real_pwd = input("Please enter your registered user name and password>>>:").strip()
        with open(r'userinfo.txt','w',encoding='utf8') as f2:
            f2.write(f'{real_name}|{real_pwd}')
            print("login was successful")
            
2.Single user login function
in_name = input("Please enter your user name>>>:").strip()
in_pwd = input("Please enter your password>>>:").strip()
with open(r'userinfo.txt','r',encoding='utf8') as f1:
    info_name,info_pwd = f1.read().split('|')
    if info_name == in_name and info_pwd ==in_pwd:
            print("Login successful")
    else:
        print("Login failed")

2. Lifting requirements:
Users can register continuously
Users can switch login by multiple accounts (multiple users). There are multiple user information in the file
ps: thinking about how to organize the data structure in the file in the case of multi-user data is relatively simple
Tip: the essence is actually the second question of yesterday's homework, but the database changes from data type to file

while True:
    print("""
    1.Registration function
    2.Login function
    3.sign out
    """)
    choice = input("Please enter your instructions>>.:").strip()
    if choice == '1':
        add_name = input("Please enter the user name you want to register>>>:").strip()
        with open(r'userinfo.txt','r',encoding='utf8') as f1:
            for line in f1:
                real_name = line.split('|')[0]
                if real_name == add_name:
                    print("User name already exists")
                    break
            else:
                add_pwd =input("Please enter your password>>>:").strip()
                with open(r'userinfo.txt','a',encoding='utf8') as f2:
                    f2.write(f'{add_name}|{add_pwd}\n')
                    print(f'user name{add_name}login was successful')

    elif choice == '2':
        in_name = input("Please enter your user name>>>:").strip()
        in_pwd = input("Please enter your password>>>:").strip()
        with open(r'userinfo.txt','r',encoding='utf8') as f1:
            for line in f1:
                info_name,info_pwd = line.strip().split('|')
                if info_name == in_name and info_pwd == in_pwd:
                    print("Login successful")
                    break
            else:
                print("Login failed")

    elif choice == '3':
        print("look forward to seeing you next time")
        break
    else:
        print("Please enter the correct instruction")

​ 3. The registration and login functions are encapsulated into functions

def login():
    in_name = input("Please enter your user name>>>:").strip()
    in_pwd = input("Please enter your password>>>:").strip()
    with open(r'userinfo.txt', 'r', encoding='utf8') as f1:
        for line in f1:
            info_name, info_pwd = line.strip().split('|')
            if info_name == in_name and info_pwd == in_pwd:
                print("Login successful")
                break
        else:
            print("Wrong user name or password")



def register():
    add_name = input("Please enter the user name you want to register>>>:").strip()
    with open(r'userinfo.txt', 'r', encoding='utf8') as f1:
        for line in f1:
            real_name = line.split('|')[0]
            if real_name == add_name:
                print("User name already exists")
                break
        else:
            add_pwd = input("Please enter your password>>>:").strip()
            with open(r'userinfo.txt', 'a', encoding='utf8') as f2:
                f2.write(f'{add_name}|{add_pwd}\n')
                print(f'user name{add_name}login was successful')

while True:
    print("""
    +++++++++++++function++++++++++++++++++++++++++
    1.Registration function
    2.Login function
    +++++++++++++++++++++++++++++++++++++++
    """)
    choice = input("Please enter your instructions>>.:").strip()
    if choice == '1':
        register()
    elif choice =='2':
        login()
    else:
        print("Please enter the correct instruction")

Cursor movement within a file

There are mainly read() and seek() methods to control the movement of file cursor

The read() method controls the movement of the file cursor

The read() method is used differently in the two operation modes (t mode and b mode)

1.t pattern(Text mode): read(n)Indicates how many characters to read
  ps:a.txt The contents of the file are:hah what are you doing ne
  eg:
  with open(r'a.txt','r',encoding='utf8') as f1:     
      print(f1.read(3))  # hah
      print(f1.read(3))  # What are you doing
2.b Mode (binary mode): read(n)Indicates how many bytes are read(English 1 byte, Chinese 3 bytes start)
  ps:a.txt The contents of the file are:hah what are you doing ne
  eg:
  with open(r'a.txt','rb') as f1:
      data = f1.read(9)
      print(data.decode('utf8'))  # hah you are
      print(f1.read(6).decode())  # What's wrong?
ps: tell()The number of bytes of the cursor can be obtained(Number of bytes from the beginning of the file content to the cursor)
  eg:
  with open(r'a.txt','r',encoding='utf8') as f1:
      print(f1.read(6))  # hah, what are you doing
      print(f1.tell())  # 12

The seek (offset, where) method controls the movement of the file cursor

1.offset Refers to the displacement of cursor movement
2.whence Mode (with 0, 1, 2 modes)>>> 1 And 2 modes can only be used in binary mode. 0 mode can only be used in binary mode t,b It's OK in both modes
  seek(n,0/1/2)  >>>When n When it is negative, the cursor moves to the left n Bytes; When n When it is a positive number, the cursor moves to the right n Bytes
  2.1 -- 0 pattern	>>>Move back based on the beginning of the file n Displacement of bytes(offset),Then start reading the following characters
		eg:
         with open(r'a.txt','r',encoding='utf8') as f1:
             f1.seek(6,0)
             print(f1.seek(6,0))  # 6 
             print(f1.read())  # What are you doing, ne
         with open(r'a.txt','rb') as f1:
             f1.seek(6,0)
             print(f1.seek(6,0))  # 6
             print(f1.read().decode())  # What are you doing, ne
  2.2 -- 1 pattern	>>>Move based on current cursor position n Displacement of bytes(offset),Then start reading the following characters
		eg:
         with open(r'a.txt','rb') as f1:
             print(f1.read(6).decode('utf8'))  # hah you
             f1.seek(3,1)  
             print(f1.read().decode())  # What, ne
         with open(r'a.txt','rb') as f1:
             print(f1.read(6).decode('utf8'))   # hah you
             f1.seek(-3,1)  
             print(f1.read().decode())  # What are you doing, ne
  2.3 -- 2 pattern	>>>Move based on end of file n Displacement of bytes(offset),Then start reading the following characters
		eg:
         with open(r'a.txt','rb') as f1:
             f1.seek(-8,2)
             print(f1.read().decode())  # What are you doing, ne
  ps:a.txt The content of the file is:hah what are you doing ne

Modification of data in the file

First of all, we should understand the principle of mechanical hard disk data storage: data modification is actually overwrite writing; The deletion of data involves the occupied state and free state. When the data is deleted, the occupied memory address is restored to the free state. In the free state, the original deleted data can be retrieved through data recovery, which reminds us to be cautious in selling electronic products. In order to prevent information leakage, the most reliable way is to delete the original data first (restore the free state), then download an irrelevant information that occupies a full memory space, and finally delete the irrelevant information (when criminals recover the data, they can only recover the irrelevant information we downloaded later)

Overwrite write

1.Essence: first read the file contents into memory, and then modify them in memory(Using the built-in method of string),Last use w Mode open file for writing
2.Advantages and disadvantages
	Advantages: the hard disk takes up only one space
     Disadvantages: when the amount of data is large, it will cause memory overflow
3.Practical operation
	with open(r'a.txt','r',encoding='utf8') as f1:
        data = f1.read()
        data1 = data.replace('nice','bad')
	with open(r'a.txt','w',encoding='utf8') as f2:
    	f2.write(data1)

rename

1.Essence: first read the contents of the file into memory, then modify it in memory, then save it to another file, then delete the original file, and finally rename the new file to the name of the original file(Will import os modular)
2.Advantages and disadvantages
	Advantages: no memory overflow
    Disadvantages: it may take up two places of the hard disk for a period of time, or it may be created in the memory without being brushed to the hard disk
3.Practical operation
    import os
    with open(r'a.txt','r',encoding='utf8') as f1,open(r'b.txt','w',encoding='utf8') as f2:
        for line in f1:
            f2.write(line.replace('bad','nice'))
    os.remove('a.txt')  # delete original file
    os.rename('b.txt','a.txt')  # rename

Function introduction

1.Define function: the function must follow the rule of defining before calling.
	Syntax structure:
	def Function name(Parameter 1, parameter 2...):
		Function body
        return Return value
2.Difference between function and loop
	Functions: same code executed repeatedly in different locations
    Loop: the same code executed repeatedly in the same position

Other read and write modes of file operation

Previously, we learned that R mode, w mode, a mode, Rb mode, WB mode, AB mode, in fact, there are r+ mode, w+ mode, a+ mode, rb+ mode, wb+ mode, ab+ mode

In file read / write mode"+"Meaning of: open a disk file for updating (reading and writing)>>>Can read and write
1.r+Mode: read / write mode
  1.1 The newly written content will overwrite the content of the original file, but it will not be completely overwritten. Write a few characters and overwrite a few characters, starting from the beginning of the file
  1.2  After writing the content, the cursor will stay behind the written file content, and then the read content is the original content that has not been overwritten
  with  open(r'a.txt','r+',encoding='utf-8') as f1:
      f1.write('0000')  # 0000 overwrites the first 4 characters
      print(f1.read())  # Read contents after 0000
2.w+Mode: write read mode  >>>because'W'You will empty the contents of the file first, and then read it. The content you read is empty
  with open(r'a.txt', 'w+', encoding='utf-8') as f1:
      f1.write('Sobbing')  # Rewrite
      f1.read()  # The read content is empty, and the cursor is at the end
3.a+Mode: the file content is not cleared, and the new content is added at the end of the content; The file pointer is at the end by default, and the read content is null
  with open(r'a.txt', 'a+', encoding='utf-8') as f1:
     f1.write('Sobbing')  # Append write
     f1.read()  # Empty
4.rb+Mode: open a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file. It is generally used for non text files such as pictures
5.wb+Mode: open a file in binary format for reading and writing. If the file already exists, open the file and edit it from the beginning, that is, the original content will be deleted; If the file does not exist, create a new file. It is generally used for non text files such as pictures.
6.ab+Mode: open a file in binary format for appending. If the file already exists, the file pointer is placed at the end of the file. If the file does not exist, create a new file for reading and writing

Tags: Python

Posted by mobile target on Fri, 01 Jul 2022 21:35:57 +0530