本章学习目的
学习如何获取系统时间
学习如何获取本机的一些系统信息
操作字典、排序、属性文件
一、如何获取时间
代码:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
python中时间日期格式化符号:
------------------------------------
%y 两位数的年份表示(00-99)
%Y 四位数的年份表示(000-9999)
%m 月份(01-12)
%d 月内中的一天(0-31)
%H 24小时制小时数(0-23)
%I 12小时制小时数(01-12)
%M 分钟数(00=59)
%S 秒(00-59)
%a 本地简化星期名称
%A 本地完整星期名称
%b 本地简化的月份名称
%B 本地完整的月份名称
%c 本地相应的日期表示和时间表示
%j 年内的一天(001-366)
%p 本地A.M.或P.M.的等价符
%U 一年中的星期数(00-53)星期天为星期的开始
%w 星期(0-6),星期天为星期的开始
%W 一年中的星期数(00-53)星期一为星期的开始
%x 本地相应的日期表示
%X 本地相应的时间表示
%Z 当前时区的名称 # 乱码
%% %号本身
"""
import time
'''
# 预期输出
2021-02-07 18:29:44
'''
print('当前时间:', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
'''
预期输出
Tue Feb 07 18:30:37 2021
'''
print('当前时间:', time.strftime('%a %b %d %H:%M:%S %Y', time.localtime()))
'''
预计输出
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")))
执行结果:
二、如何创建删除文件夹
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 系统操作
import os
print('当前目录:', os.getcwd())
# 创建文件夹
def create_directory_if_not_exist(directory_path):
try:
os.mkdir(directory_path)
except IOError:
print(f'文件夹已经存在:{directory_path}')
else:
print(f'{directory_path}创建成功')
# 删除文件夹
def remove_directory(directory_path):
try:
os.rmdir(directory_path)
except IOError:
print(f'文件夹不存在:{directory_path} 无法删除')
else:
print(f'{directory_path}文件夹删除成功')
# 显示文件夹下的文件
def list_files(directory_path):
try:
file_array = os.listdir(directory_path)
except IOError:
print(f'文件夹不存在:{directory_path} 无法展示')
else:
print(f'{directory_path}文件夹下的文件(夹)有:{file_array}')
# 在本项目temp文件下创建一个叫one的文件夹
create_path = '../temp/one'
create_directory_if_not_exist(create_path)
list_path = '../temp'
list_files(list_path)
remove_directory(create_path)
执行结果:
三、如何操作属性文件(properties文件)呢
代码:
#!/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('#')]
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
# 读取properties文件内容,并转化成json格式对象
# app.properties内容为 e
# app.name=python-project
properties = Properties("../resources/app.properties").get_properties_by_file()
# 转化后打印出来的是
# 预计输出
# {'app': {'name': 'python-project'}}
print(properties)
# 预计输出
# {
# "app": {
# "name": "python-project"
# }
# }
print(json.dumps(properties, indent=4))
执行结果:
四、如何操作字典(Dictionary)
代码:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
dict1 = {'name': 'Jake'}
dict2 = {'title': '修炼爱情', 'author': '林俊杰'}
'''
预期输出:
{'name': 'Jake'}
title:修炼爱情
author:林俊杰
'''
print(dict1)
print(f'title:{dict2["title"]}')
print(f'author:{dict2["author"]}')
执行结果:
五、如何对数组进行排序
代码:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
1. 数字排序
"""
num_array = [5, 3, 9, 18, 1, 46]
'''
预期输出
[1, 3, 5, 9, 18, 46]
'''
print(sorted(num_array))
'''
预期输出
[1, 3, 5, 9, 18, 46]
'''
num_array.sort()
print(num_array)
"""
2. 字符排序
"""
'''
预期输出
['0', 'A', 'BA', 'aaa', 'bac']
'''
str_array = ['aaa', 'bac', '0', 'A', 'BA']
print(sorted(str_array))
'''
预期输出
排序时忽略大小写
['0', 'A', 'aaa', 'BA', 'bac']
'''
str_array = ['aaa', 'bac', '0', 'A', 'BA']
print(sorted(str_array, key=str.lower))
执行结果: