Purpose of this chapter

Learn how to get system time

Learn how to get some system information on the machine

Manipulating dictionaries, sorting, properties files

How to acquire time

Code:

#! /usr/bin/python
# -*- coding: UTF-8 -*-

""" Time and date formatting symbols in Python: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - % y year of double-digit said (00-99) % y said four digits of the year (000-9999) % m (01-12) % d month in a day in the % H (0-31) Hours in 24-hour system (0-23) %I Hours in 12-hour system (01-12) %M Minutes (00=59) %S seconds (00-59) %A Simplified local week %A Complete local week %b Simplified local month %b Complete local month %c The corresponding local date representation and time represent %j day of the year (001-366) %p local A.M. Or P.M. %U number of weeks in a year (00-53) Sunday is the beginning of the week %w week (0-6), Sunday is the beginning of the week %W Number of weeks in a year (00-53) Monday is the beginning of the week %x Local date represents %x local time represents %Z Name of the current time zone # garbled %% % itself ""

import time

"# Expected output 2021-02-07 18:29:44"
print('Current time:', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))

Tue Feb 07 18:30:37 2021 Tue Feb 07 18:30:37 2021
print('Current time:', time.strftime('%a %b %d %H:%M:%S %Y', time.localtime()))

"Expected output 1614508283.0"
original_time = 'Tue Feb 28 18:31:23 2021'
print(time.mktime(time.strptime(original_time, "%a %b %d %H:%M:%S %Y")))

Copy the code

Execution Result:

How to create and delete folders

#! /usr/bin/python
# -*- coding: UTF-8 -*-

# System operation

import os

print('Current directory:', os.getcwd())


Create folder
def create_directory_if_not_exist(directory_path) :
    try:
        os.mkdir(directory_path)
    except IOError:
        print(F 'folder already exists:{directory_path}')
    else:
        print(f'{directory_path}Created successfully ')


# delete folder
def remove_directory(directory_path) :
    try:
        os.rmdir(directory_path)
    except IOError:
        print(F 'folder does not exist:{directory_path}Unable to delete ')
    else:
        print(f'{directory_path}Folder deleted successfully ')


Display the files under the folder
def list_files(directory_path) :
    try:
        file_array = os.listdir(directory_path)
    except IOError:
        print(F 'folder does not exist:{directory_path}Unable to show ')
    else:
        print(f'{directory_path}The files (folders) under the folder are:{file_array}')


Create a folder named one under the project temp file
create_path = '.. /temp/one'
create_directory_if_not_exist(create_path)

list_path = '.. /temp'
list_files(list_path)

remove_directory(create_path)


Copy the code

Execution Result:

How to operate the properties file

Code:

#! /usr/bin/python
# -*- coding: UTF-8 -*-

import json


class Properties(object) :
    def __init__(self, file_path) :
        self.file_path = file_path
        self.properties = {}

    def get_dict(self, keyName, dictName, value) :
        if keyName.find('. ') > 0:
            key = keyName.split('. ') [0]
            dictName.setdefault(key, {})
            return self.get_dict(keyName[len(key) + 1:], dictName[key], value)
        else:
            dictName[keyName] = value
            return

    def get_properties_by_file(self) :
        try:
            file = open(self.file_path, 'r')
            for line in file.readlines():
                line = line.strip().replace('\n'.' ')
                if line.find("#") != -1:
                    line = line[0:line.find(The '#')]
                if line.find('=') > 0:
                    words = line.split('=')
                    words[1] = line[len(words[0]) + 1:]
                    self.get_dict(words[0].strip(), self.properties, words[1].strip())
        except Exception as e:
            raise e
        else:
            file.close()
        return self.properties


Read the contents of the properties file and convert it to a JSON formatted object
# app.properties content is e
# app.name=python-project

properties = Properties(".. /resources/app.properties").get_properties_by_file()

# What is printed after conversion is
# Expected output
# {'app': {'name': 'python-project'}}
print(properties)

# Expected output
# {
# "app": {
# "name": "python-project"
#}
#}
print(json.dumps(properties, indent=4))

Copy the code

Execution Result:

How to operate a Dictionary

Code:

#! /usr/bin/python
# -*- coding: UTF-8 -*-

dict1 = {'name': 'Jake'}
dict2 = {'title': 'Cultivate love'.'author': 'Jj Lin'}

"" Expected output: {'name': 'Jake'} title:"
print(dict1)
print(f'title:{dict2["title"]}')
print(f'author:{dict2["author"]}')

Copy the code

Execution Result:

How to sort an array

Code:

#! /usr/bin/python
# -*- coding: UTF-8 -*-

1. Numeric sorting
num_array = [5.3.9.18.1.46]

Expected output [1, 3, 5, 9, 18, 46]
print(sorted(num_array))

Expected output [1, 3, 5, 9, 18, 46]
num_array.sort()
print(num_array)

2. Character sorting

Expected output ['0', 'A', 'BA', 'AAA ',' BAC ']
str_array = ['aaa'.'bac'.'0'.'A'.'BA']
print(sorted(str_array))

"' expected output when ordering ignore case [' 0 ', 'A', 'aaa', 'BA', 'America'] ' ' '
str_array = ['aaa'.'bac'.'0'.'A'.'BA']
print(sorted(str_array, key=str.lower))

Copy the code

Execution Result: