ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Day014 - 常用系统模块

2021-07-30 22:31:05  阅读:207  来源: 互联网

标签:文件 常用 datetime licenses tm 模块 time print Day014


os模块常用函数

os.getcwd() - 获取当前工作目录

os.listdir(文件夹路径) - 获取指定文件夹所有文件的名称

os.path.abspath(’./’) - 获取指定相对路径的绝对路径

import os

print(os.getcwd())

print(os.listdir('./'))

print(os.path.abspath('./'))

time模块

时间戳

  • 指定时间到1970-01-01 00:00:00(格林威治时间)的时间差(单位:秒)来表示时间的方式就是时间戳。

time.time()

  • 获取当前时间(世界协调时)
print(time.time())  # 获取当前时间,返回值为时间戳

time.localtime()

  • 获取当前时间的本地时间,返回时间戳

time.localtime(时间戳)

  • 将时间戳对应的时间转换成本地时间,返回结构体时间
print(time.localtime())
print(time.localtime(1627612746.222818))
# time.struct_time(tm_year=2021, tm_mon=7, tm_mday=30, tm_hour=10, tm_min=39, tm_sec=6, tm_wday=4, tm_yday=211, tm_isdst=0)

time.sleep()

  • 程序休眠指定时间,单位秒
time.sleep(0)

time.strftime()

  • 结构体时间转换成字符串时间
%Y%m%d%H%I%M%S
时(24制式)时(12制式)
t1 = time.localtime()
result = time.strftime('%z %Y-%m-%d %H:%M:%S', t1)
print(result)  # +0800 2021-07-30 11:06:08

time.strptime(字符串时间, 时间格式)

  • 将字符串时间转换成结构体时间
t2 = '2020-10-20'
result = time.strptime(t2, '%Y-%m-%d')
print(f'周{result.tm_wday + 1}')  # 周2

将字符串时间转换成时间戳(先将字符串时间转换成结构体时间)

result = time.mktime(t1)
print(result)

datetime模块

datetime.datetime类

  • 处理包含年月日时分秒的时间

创建datetime时间对象

  • datetime(year, month, day, hour=0, minute=0, second=0)
t1 = datetime.datetime(2018, 10, 10, 14, 23, 45)
print(t1)  # 2018-10-10 14:23:45

获取时间属性

  • 时间对象.属性
print(t1.year, t1.minute)  # 2018 23

获取当前时间

t2 = datetime.datetime.now()
print(t2)  # 2021-07-30 11:37:39.852374

将时间对象转换成结构体时间

t3 = t2.timetuple()
print(t3)  # time.struct_time(tm_year=2021, tm_mon=7, tm_mday=30, tm_hour=11, tm_min=40, tm_sec=8, tm_wday=4, tm_yday=211, tm_isdst=-1)

将时间对象转换成字符串时间

t4 = t2.strftime('%Y-%m-%d %H:%M:%S')
print(t4, type(t4))  # 2021-07-30 11:42:31 <class 'str'>

将字符串时间转换成时间对象

t5 = datetime.datetime.strptime(t4, '%Y-%m-%d %H:%M:%S')
print(t5, type(t5))  # 2021-07-30 11:47:59 <class 'datetime.datetime'>

datetime.timedelta类

  • 主要用于时间的加减操作
t1 = '2020-01-01 00:00:00'
t2 = datetime.datetime.strptime(t1, '%Y-%m-%d %H:%M:%S')
print(t2, type(t2))  # 2020-01-01 00:00:00 <class 'datetime.datetime'>

t3 = t2 + datetime.timedelta(days=10)  # 增加10天
print(t3)  # 2020-01-11 00:00:00

t4 = t3 + datetime.timedelta(weeks=1)  # 增加一周时间
print(t4)  # 2020-01-18 00:00:00

hashlib

  • 用于生成数据的hash摘要

  • hash加密算法主要有:md5 和 shaxx

  • hash加密的特点:

    • 不可逆(通过源数据加密后(产生的摘要)无法还原);
    • 相同的数据通过相同的算法产生的摘要(密文)是一样的;
    • 不同大小的数据在使用相同的算法产生的摘要的长度一致;

使用hashlib产生数据对象

  • 根据算法创建hash对象
# hashlib.算法名()
hash1 = hashlib.md5()
  • 添加数据
# hash对象.update(二进制数据)
pw = '123456'
hash1.update(pw.encode())
  • 获取摘要
result = hash1.hexdigest()
print(result)  # e10adc3949ba59abbe56e057f20f883e
hash2 = hashlib.sha256()
ssh = '123456'
hash2.update(ssh.encode())
result = hash2.hexdigest()
print(result)

Python二进制数据类型 - bytes

字符串和bytes相互转换

  1. str -> bytes
  • bytes(‘字符串’,‘utf-8’)
  • b’字符集’
  • 字符串.encode()
# 字符串转二进制
print(bytes('abc', 'utf-8'))  # b'abc'
b1 = b'abc'
print(b1, type(b1))  # b'abc' <class 'bytes'>
  1. bytes -> str
  • str(二进制数据,‘utf-8’)
  • 二进制数据.decode()
# 二进制转字符串
print(str(b1, 'utf-8'))  # abc
print(b1.decode())  # abc

文件操作

数据存储

  • 程序中保存的数据默认都是存储在运行内存中,运行内存中的数据在程序结束后都会被释放;
  • 如果希望程序运行过程中产生的数据在程序结束后不被销毁,就需要将数据存储在磁盘中;
  • 将数据存储到磁盘的郭程程叫数据持久化(或者叫数据本地化)
  • 基本原理 - 将数据通过文件存储到磁盘中

文件操作(文件内容的读写)

  • 将程序中的数据通过文件存储到磁盘中
  • 怎么在程序中使用保存在文件中的数据

文件操作基本步骤

打开文件

  • open(文件路径, 读写模式, encoding=文件编码方式) - 以指定方式打开指定文件,创建文件对象

    • 文件路径

      • 文件在计算机中的位置信息,以字符串的形式提供值;

      • 绝对路径:文件在计算机里的全路径;

      • 相对路径:. 表示当前代码文件的目录

        ​ … 表示当前目录的上层目录

    • 读写模式

      • 设置打开文件后支持的是读操作还是写操作,以及设置操作数据类型(是字符串还是二进制)

      • 第一组值:r(read) - 只读

        ​ w(write) - 只写,先清空源文件;

        ​ a(append) - 只写,保留源文件,在后面追加;

      • 第二组值:t - 数据类型是字符串(t可以省略)

        ​ b - 数据类型是bytes

    • encoding

      • 文件编码方式,默认为utf-8;一般只要求打开的编码方式与文件本身编码方式一致;
      • 式与文件本身编码方式一致;
# 参数1:路径
licenses = open(r'D:\StudyExperience\Python Data Analysis\01语言基础\Day14 - 常用系统模块\licenses.txt')
licenses = open('./licenses.txt')
licenses = open('../Day14 - 常用系统模块/licenses.txt')

# 参数2:读写模式
# r -   只读
licenses = open('./licenses.txt', 'r')
licenses.read()
# licenses.write('abc')  # io.UnsupportedOperation: not writable

# w -   只写;会清空
licenses = open('./licenses.txt', 'w')
licenses.write('abc')
# licenses.read()  # io.UnsupportedOperation: not readable

# a -   只写;保留源文件并追加
licenses = open('./licenses.txt', 'a')
# licenses.read()  # io.UnsupportedOperation: not readable
licenses.write('abc')

# t -   读写数据的类型是字符串
licenses = open('./licenses.txt', 'rt')
result = licenses.read()
print(type(result))  # <class 'str'>

# b -   读写数据的类型是二进制
licenses = open('./licenses.txt', 'rb')
result = licenses.read()
print(type(result))  # <class 'bytes'>

licenses = open('./licenses.txt', 'ab')
# licenses.write('abc')  # TypeError: a bytes-like object is required, not 'str'
licenses.write(b'abc')

读写文件

文件对象.read()

  • 文件对象.read() - 从读写位置开始读到文件结尾(读写位置默认在文件开头)
  • 文件对象.seek() - 设置读写位置到文件开头
  • 文件对象.readline() - 读取从光标位置开始的第一行内容,如果没有内容会返回空串;
  • 文件对象.readlines() - 读取文件的每一行,返回一个由每行构成元素的列表;

文件对象.write()

  • 文件对象.write() - 写文件,从哪开始写和打开文件的方式有关;

关闭文件

文件对象.close()

数据持久化

数据持久化的基本步骤

  1. 确定需要持久化的数据(确定哪个数据在下一次运行程序需要使用);
  2. 创建文件保存数据初始值;
  3. 在程序中需要这个数据的时候从文件里读取;
  4. 如果数据发生改变,要将最新的数据写回文件;
# 写一个程序,打印程序运行次数
conf = open('./file/config.txt', 'rt', encoding='utf-8')
count = int(conf.read())
count += 1
print(count)

conf = open('./file/config.txt', 'w', encoding='utf-8')
conf.write(str(count))
# 练习:添加学生,并且在添加文成后显示所有学生信息(只需要学生姓名)

while True:
    stu = open('./file/stu.txt', 'rt', encoding='utf-8')
    num = str(stu.read())
    print(num)
    in_put = input('请输入姓名:')
    if in_put == 'q':
        break
    stu = open('./file/stu.txt', 'at', encoding='utf-8')
    stu.write(f' {in_put}')
# 在上题的基础上将学生姓名打印成列表
while True:
    in_put = input('请输入姓名:')
    if in_put == 'q':
        break
    stu = open('./file/stu.txt', encoding='utf-8')
    num = eval(stu.read())
    num.append(in_put)
    print(num)

    stu = open('./file/stu.txt', 'w', encoding='utf-8')
    stu.write(str(num))

标签:文件,常用,datetime,licenses,tm,模块,time,print,Day014
来源: https://blog.csdn.net/qq_20814305/article/details/119257059

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有