Python common system modules and file operations

Python common system modules and file operations

1 . time module

time stamp
The time stamp is the time difference (in seconds) between the specified time and 0:0:0:0 (Greenwich mean time) on January 1, 1970

Note: there is a time difference of 8 hours between Greenwich mean time and Beijing time

4 bytes (timestamp storage time)
16 bytes (time stored in string)

  1. time.time() - get the current time

    print(time.time())      # 1627611728.5696352
    
  2. time.localtime() - get the local time of the current time and return the structure time

    time. Localtime (timestamp) - converts the time corresponding to the timestamp to local time

    t1 = time.localtime()
    print(t1.tm_year, t1.tm_mon, t1.tm_mday, t1.tm_hour, t1.tm_min, t1.tm_sec)
    # 2021 8 4 18 56 1
    print(time.localtime(0))
    # time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=8, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)
    
  3. time. Sleep - the specified time for the program to sleep, in seconds

  4. time. Strftime (time format, structure time) - structure time to string time

    %Y - year
    %m - month
    %d - day
    %H - hour (24-hour system)
    %I - hour (12 hour system)
    %M - min
    %S - seconds
    %p - AM, PM (am, PM)
    %a - abbreviation of week
    %A - spelling of English words on Monday
    %b - abbreviation of month
    %B - month English spelling

    result = time.strftime('%Y year%m month%d day %H:%M:%S', t1)
    print(result)
    # August 4, 2021 18:56:01
    result = time.strftime('%m month%d day %p%I:%M %B', t1)
    print(result)
    # August 4 PM06:56 August
    
  5. Convert string time to struct time

    time. Strptime (string time, time format)

    t3 = time.strptime('2010-10-2', '%Y-%m-%d')
    print(f'week{t3.tm_wday + 1}')  #Week 6
    print(t3) 
    # time.struct_time(tm_year=2010, tm_mon=10, tm_mday=2, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=275, tm_isdst=-1)
    
  6. Convert string time to timestamp (convert string time to struct time first)

    time. Mktime (structure time) - converts the structure time to a timestamp

    result = time.mktime(t3)
    print(result)   # 1285948800.0
    

2 . datetime module

  1. datetime type - process the time containing month, day, hour, minute and second

    1) Create datetime object

    # datetime(year, month, day, hour=0, minute=0, second=0)
    t1 = datetime(2010, 10, 2)
    print(t1)       # 2010-10-02 00:00:00
    
    t2 = datetime(2011, 9, 30, 11, 15, 30)
    print(t2)       # 2011-09-30 11:15:30
    
    1. Get time attribute
    # Time object year, time object month,...
    print(t2.month)  # 9
    print(t2.hour)  # 11
    
    1. Get current time
    t3 = datetime.now()
    print(t3)   # 2021-08-04 19:09:35.467140
    
    1. Convert datetime to struct time
    t4 = t3.timetuple()
    print(t4)   
    #time.struct_time(tm_year=2021, tm_mon=8, tm_mday=4, tm_hour=19, tm_min=9, tm_sec=35, tm_wday=2, tm_yday=216, tm_isdst=-1)
    
    1. Convert datetime to string time
    st5 = t3.strftime('%Y year%m month%d day %a')
    print(st5)   #August 4, 2021 Wed
    
    1. Convert string time to datetime
    str6 = '2003-7-1'
    t5 = datetime.strptime(str6, '%Y-%m-%d')
    print(t5)   # 2003-07-01 00:00:00
    
  2. timedelta - mainly used for addition and subtraction of time

t6 = t5 + timedelta(days=45)
print(t6)   # 2003-08-15 00:00:00
t7 = t5 - timedelta(hours=8)
print(t7)   # 2003-06-30 16:00:00
t8 = t5 + timedelta(days=1, hours=5, minutes=15)
print(t8)   # 2003-07-02 05:15:00

3 . hashlib module

hashlib module - hash summary for generating data

# 1. Create a hash object according to the algorithm
# hashlib. Algorithm name ()
hash = hashlib.md5()

# 2. Add data
# hash object Update (binary data)
pw = '123456'
hash.update(pw.encode())
# hash.update('abc'.encode())

# f = open('images/test.txt', 'rb')
# hash.update(f.read())

# 3. Get summary
result = hash.hexdigest()
print(result)
# e10adc3949ba59abbe56e057f20f883e

hash encryption algorithms mainly include md5 and shaxxx

  1. Features of hash encryption:
    a. Irreversible (cannot be restored after the original data is encrypted)
    b. The digest (ciphertext) generated by the same data through the same algorithm is the same
    c. Data of different sizes are consistent in the length of the summary generated by the same algorithm

  2. Use hashlib to generate a summary of the data

python binary data type - bytes

Conversion between string and bytes

  1. str -> bytes
    Method 1: bytes (string 'utf-8')
    Method 2: b 'character set'
    Method 3: string encode()

  2. bytes -> str
    Method 1: str (binary data, 'utf-8')
    Method 2: binary decode()

# String to binary
print(bytes('abc', 'utf-8'))

b1 = b'abc'
print(type(b1))

str1 = 'anc'
print(str1.encode())

# Binary to string
print(str(b1, 'utf-8'))
print(b1.decode())

4 . File operation

  1. Data storage

    The data saved in the program is stored in the running content by default, and the data in the running memory will be released at the end of the program.
    If you want the data generated during the operation of the program not to be destroyed after the end of the program, you need to store the data on disk.

    The process of storing data to disk is called data persistence and data localization.
    Basic principle of data persistence - store data to disk through files.

  2. File operation (operation file content)

    File operation mainly solves two problems:
    a. How to store the data in the program to disk through files
    b. How to use the data stored in the file in the program

  3. Basic steps of file operation

    Step 1: open the file
    Open (file path, read-write mode, encoding = file encoding method) - open the specified file in the specified way and return the file object
    1) File path - information about the location of the file on the computer, providing a value in the form of a string.
    a. Absolute path: the full path of the file on the computer
    b. Relative path:- Indicates the current directory (the directory where the current code file is located)/ Can be omitted
    ... - indicates the upper level directory of the current directory
    2) Read / write mode - set whether to support read or write operations after opening a file; Sets whether the type of operation data is string or binary
    First set of values:
    r - read only
    w - write only; Empty the original file first
    a - write only; Retain the contents of the original file and append data later
    Second set of values:
    T - the data type is a string (t can be omitted)
    b - the data type is bytes
    'r' == 'rt' == 'tr'

    Note: if it is a text file, it can be opened in t or b. if it is a binary file, it can only be opened in b

    3) Encoding - file encoding method (the open encoding method must be consistent with the file encoding method)
    When the file is opened in b mode, encoding cannot be assigned
    Step 2: read and write files
    File object read()
    File object Write (data)

    Step 3: close the file
    File object close()

  4. Open a file that does not exist

    If you open a nonexistent file by reading, an error will be reported;
    If you open a nonexistent file by writing, no error will be reported;

  5. Read / write mode:+

    Usage: r+ / w+ / a + - read / write operation

  6. Open file through file context

    File object = open()
    File object read() / file object write()
    File object close()

    with open() as file object:
    File object read() / file object write()

5 . Read / write operation

  1. Read operation
    File object read() - read from the read-write location to the end of the file (the read-write location is at the beginning of the file by default)
    File object readline() - read from the read-write position to the end of a line (valid only when reading a text file)
    File object readlines() - read line by line. Finish reading

    f = open('test.py', encoding='utf-8')
    result = f.read()
    print(result)
    
    print('-------------------------Gorgeous dividing line-------------------------------')
    f.seek(0)    # Set the read / write location to the beginning of the file
    print(f.read())
    
  2. Write operation

    File object write()
    File object writelines()

    f = open('test.py', 'a', encoding='utf-8')
    f.write('\nabc\n123\n456')
    f.writelines(['abc', '123', '456'])
    f.close()
    

6 . Data persistence operation

Basic steps of data persistence:

Step 1: determine the data to be persisted (determine which data to use the next time you run the program)
Step 2: create a file to save the initial data value
Step 3: read the data from the file when the data is needed in the program
Step 4: if the data changes, write the latest data back to the file

# Exercise 1: write a program and print the number of times the program runs
"""
Print the program for the first time: 1
 Print the program for the second time: 2
 Print the program for the third time: 3
"""
f = open('count.txt', 'rt', encoding='utf-8')
count = int(f.read())
count += 1
print(count)

f = open('count.txt', 'w', encoding='utf-8')
f.write(str(count))

# Exercise 2: add students and display all student information after adding (only student name is required)
"""
Please enter student name: Xiao Ming
 Xiao Ming   ['Xiao Ming']

Please enter student name:floret
 Xiaoming Xiaohua   ['Xiao Ming', 'floret']

Please enter student name:q
((end of program)

Please enter student name: Zhang San
 Xiao Ming Xiao Hua Zhang San   ['Xiao Ming', 'floret', 'Zhang San']

Please enter student name: Li Si
 Xiao Ming, Xiao Hua, Zhang San, Li Si    ['Xiao Ming', 'floret', 'Zhang San', 'Li Si'] 

Please enter student name:q
((end of program)
"""
# Requirement 1:
# while True:
#     name = input('Please enter student name: ')
#     if name == 'q':
#         break
#
#     f = open('students.txt', 'a', encoding='utf-8')
#     f.write(f'{name} ')
#
#     f = open('students.txt', encoding='utf-8')
#     print(f.read())

# Requirement 2:
while True:
    name = input('Please enter student name:')
    if name == 'q':
        break

    f = open('students2.txt', encoding='utf-8')
    all_student = (f.read())    # '[]', "['name']"
    # all_student.append(name)
    print(all_student)

    f = open('students2.txt', 'w', encoding='utf-8')
    f.write(str(all_student))

Keywords: Python

Added by kritro on Mon, 03 Jan 2022 03:45:15 +0200