Day14 File Operation

Day14 File Operation

  1. Usage of hashlib

    1. Characteristics of hash encryption

      • The hash algorithm produces an irreversible summary. (The original text cannot be obtained in ciphertext)
      • Only the summaries of the same data from the same algorithm are consistent
      • The resulting summary is the same size (length) regardless of the size of the original data.
    2. Generate hash summary

      1. Create hash object by algorithm: hashlib. Algorithm name ()
      Algorithm name: md5,shaXXX
      hash = hashlib.sha512()
      1. Add data

        • hash object. Update (data)

        • Note: The data must be binary and the type is bytes

          # hash.update(bytes('123456', encoding='utf-8'))
      2. Conversion between binary and string

        • String to Binary:

          bytes(Character string, encoding='utf-8')
          Character string.encode()
        • Binary to String:

          str(Binary, encoding='utf-8')
      3. Get Summary

        result = hash.hexdigest()
        print(result)   # e10adc3949ba59abbe56e057f20f883e
  2. Operation of Files

    1. Basic flow of file operation: open file - > operate file (read, write) - > close file

    2. Open File

      • open(file, mode='r', *, encoding=None) - Opens the specified file in the specified way and returns a file object

        • File - Location information (file path), string of the file you want to open on your computer

          Absolute path: The full path of the file in the computer (typically written from disk)

          Relative path:. - Represents the current directory (the folder where the current code file is located),. / Can be omitted
          ... - indicates the upper directory of the current directory

        • mode - The way a file is opened, which determines what operations can be performed on the file and the type of operation data after the file is opened.

          The first group:'r','w','a'- controls subsequent actions (read or write)

          'r'- Read-only
          'w'- Write-only, empties the contents of the original file
          'a'- Write-only, preserves the original file contents

          Group 2:'t','b'- Control the type of operation data
          't'- The data returned by the read operation and the data written by the write operation are strings (str)
          'b'- The data returned by the read operation and the data written by the write operation are binary (bytes)

          The first group must select one, the second group can not, when not selected, the default is t
          Note: Binary file must be opened with b

        • Encoding - The encoding of text files (you need to ensure what encoding is used to write the data and decode it when reading the data)

          utf-8 is generally used, but gbk is the default encoding method for many windows text

          Note: Enoding should only be considered if the text file is opened as t

          =========Absolute path===========
          open(r'/Users/yuting/Teaching/python2103/01 Language Foundation/day14-Exception capture and file operations/contract.txt')
          =========Relative Path==========
          open('../day14-Exception capture and file operations/contract.txt')
          ========r Is read-only=========
          f = open('./contract.txt', 'r')

          f.write('abc')     # io.UnsupportedOperation: not writable
          ========a Is write-only and preserves the contents of the original file=======
          f = open('./contract.txt', 'a')
          #    # io.UnsupportedOperation: not readable
          ========w Is write-only and empties the contents of the original file=======
          f = open('./contract.txt', 'w')
    # io.UnsupportedOperation: not readable
          =========t,Operation data is a string======
          f = open('./contract.txt', 'rt')
          content =
          print(type(content))     # <class 'str'>
          =========b,Operational data is binary======
          f = open('./contract.txt', 'rb')
          content =
          print(type(content))    # <class 'bytes'>
          f = open('day7 task.mp4', 'rb')

    3. Close File

      • File object. close()

        f.close()   # ValueError: read of closed file
    4. operation

      1. Read operation

        • File object. read() - Start at the read-write location and end of the file. (The read and write location defaults to the beginning of the file)

        • File object. readline() - Start at the read-write position and end of a line

          f = open('./res/a.txt', encoding='utf-8')
       # Move the read and write location to the beginning of the file


          print(f.readlines())    # ['Bright moonlight in front of bed, \n','Frost on the ground suspected. \n','Raise your head to the moon, \n','Look down and think of your home']
      2. Write operation

        • File object. Write (data) - Writes data to a specified file

          f = open('./res/a.txt', 'w', encoding='utf-8')
  3. Data persistence

    1. Method of data persistence

      • Use a file to hold data that needs to be persisted

      • Read this data when it is needed in the program

      • If the data changes, you need to write the latest data back to the file

        # def count_pro():
        #     t = open('./test', mode='rw')
        #     num =
        #     t.close()
        #     num += 1
        #     t.write(num)
        #     print(
        # count_pro()
        f = open('./test')
        count = int(
        count += 1
        f = open('./test', 'w')
    2. eval function

      result = eval('100')
      print(result, type(result))
      result = eval('12.5')
      print(result, type(result))
      result = eval('[10, 20, 30]')
      print(result, type(result))
      result = eval('100')
      print(result, type(result))


import hashlib

def login():
    name = input('enter one user name:')
    pwd = input('Please input a password:')
    hash_pwd = hashlib.md5()
    f = open('./test', encoding='utf-8')
    text = eval(
    for x in text:
        if name in x.keys() and hash_pwd.hexdigest() in x.values():
            print('Landing Success')
            return True
    print('Logon Failure')

def Registration():
    name = input('Please enter your name:')
    pwd = input('Please input a password')
    hash_pwd_in = hashlib.md5()
    f = open('./test', encoding='utf-8')
    text = eval(
    for x in text:
        if name in x.keys():
            print('User name already exists,Please re-register')
        f = open('./test', 'w', encoding='utf-8')
        print('login was successful')

while True:
    print('              Student Management System Login Interface              ')
    print('              ❀ 1.Sign in')
    print('              ❀ 2.Registration')
    print('              ❀ 3.Sign out')
    num = int(input('Please select:'))
    if num == 1:
    if num == 2:
    if num == 3:

Added by dsaba on Thu, 10 Feb 2022 05:20:09 +0200