2020Python work nine - basic application functions
@2020.3.17
Use function overrides
# 1, written document editing, when you call the function, passing three parameters (modify the file path, to modify the contents of the revised content) modification to complete the file
import os def file(file_path, old_content, new_content): with open(r'{}'.format(file_path),mode='rb') as read_f,\ Open (R & lt ' {} .swap ' .format (file_path, MODE = ' WB ' )) AS write_f: # .swap naming convention is Linux system, the beginning of the file is a hidden '.' the while True: res = read_f.readline().decode('utf-8') if old_content in res: res2 = res.replace('{}'.format(old_content),'{}'.format(new_content)) write_f.write(bytes('{}'.format(res2),encoding='utf-8')) else: write_f.write (bytes ( ' {} ' .format (RES), encoding = ' UTF-. 8 ' )) BREAK The os.remove ( ' {} ' .format (file_path)) # delete the original file os.rename ( ' { .swap} ' .format (file_path), ' {} ' .format (file_path)) # new file is renamed to the original file name file_path = INPUT ( ' Please INPUT file path: ' ) old_content = input('please input content that needs to rewrite:') new_content = input('please input new content:') if file_path and old_content and new_content: mesg = File (file_path, old_content, NEW_CONTENT) Print (mesg) the else : Print ( ' modification failure Please try again " )
# 2, written in tail tool
def tail(): cmd = INPUT ( ' enter the command: ' ) .strip () IF cmd == ' tail -f the access.log ' : with open(r'access.log', 'a+b') as f: f.write(bytes('{}\n'.format(cmd), encoding='utf-8')) continue else: with open(r'access.log', 'rb') as f: f.write(bytes('{}\n'.format(cmd), encoding='utf-8')) tail()
# 3, writing a login function
def login(inp_username,inp_password): Open with ( ' user.txt ' , MODE = ' RT ' , encoding = ' UTF-. 8 ' ) AS F: for Line in F: # authentication, the user name and password entered with the contents read out for comparison Print ( Line, End = '' ) # Egon: 123 \ n- username, password = line.strip () Split (. ' : ' ) IF inp_username == username and inp_password == password: Print ( ' Login successfull ' ) BREAK the else : Print ( ' account number or password is incorrect ' ) inp_username=input('your name>>: ').strip() inp_password=input('your password>>: ').strip() login(inp_username,inp_password)
# 4, written registration function
def register(name,pwd): with open('register.txt',mode='at',encoding='utf-8') as f: f.write('{}:{}\n'.format(name,pwd)) name=input('your name>>: ') pwd=input('your name>>: ') register(name,pwd)