Python-常用系统模块和文件操作

Python-常用系统模块和文件操作

1.时间戳

用指定时间到1970年1月1日0时0分0秒(格林威治时间)的时间差(单位是秒)来表示时间的方式就是时间戳

注:格林威治时间和北京时间有8个小时的时差

4个字节(时间戳存储时间)
16个字节(用字符串存储时间)

1)time.time() - 获取当前时间

print(time.time())      # 1627611728.5696352

2)time.localtime()

time.localtime() - 获取当前时间的本地时间,返回结构体时间
time.localtime(时间戳) - 将时间戳对应的时间转换成本地时间

t1 = time.localtime()
print(t1.tm_year, t1.tm_mon, t1.tm_mday, t1.tm_hour, t1.tm_min, t1.tm_sec)

print(time.localtime(0))

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

time.sleep(2)
print('========')

4)time.strftime(时间格式, 结构体时间) - 结构体时间转字符串时间

xxxx年xx月xx日 xx:xx:xx
“”"
%Y - 年
%m - 月
%d - 日
%H - 时(24小时制)
%I - 时(12小时制)
%M - 分
%S - 秒
%p - AM、PM(上午、下午)
%a - 星期英文单词缩写
%A - 星期英文单词全拼
%b - 月份英文缩写
%B - 月份英文全拼

result = time.strftime('%Y年%m月%d日 %H:%M:%S', t1)
print(result)

# xxxx-xx-xx xx:xx:xx
result = time.strftime('%Y-%m-%d %H:%M:%S', t1)
print(result)

result = time.strftime('%m月%d日 %p%I:%M %B', t1)
print(result)

5)将字符串时间转换成结构体时间

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

t2 = '2010-10-2'
t3 = time.strptime('2010-10-2', '%Y-%m-%d')
print(f'周{t3.tm_wday + 1}')
print(t3)

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

time.mktime(结构体时间) - 将结构体时间转换成时间戳

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

2.datetime类型

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

1)创建datetime时间对象
datetime(year, month, day, hour=0, minute=0, second=0)
from datetime import datetime, timedelta

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

# 2) 获取时间属性
# 时间对象.year、时间对象.month、...
print(t2.month)
print(t2.hour)

# 3) 获取当前时间
t3 = datetime.now()
print(t3)

# 4) 将datetime转换成结构体时间
t4 = t3.timetuple()
print(t4)

# 5) 将datetime转换成字符串时间
st5 = t3.strftime('%Y年%m月%d日 %a')
print(st5)

# 6) 将字符串时间转成datetime
str6 = '2003-7-1'
t5 = datetime.strptime(str6, '%Y-%m-%d')
print(t5)   # 2003-07-01 00:00:00

# 2. timedelta   -  主要用于时间的加减操作
t6 = t5 + timedelta(days=45)
print(t6)   # 2003-08-15 00:00:00

t7 = t5 - timedelta(hours=8)
print(t7)

t8 = t5 + timedelta(days=1, hours=5, minutes=15)
print(t8)

3.hashlib模块

hashlib模块 - 用于生成数据的hash摘要
hash加密算法主要有:md5 和 shaxxx

1)hash加密的特点:

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

2)使用hashlib产生数据的摘要

import hashlib
# 1. 根据算法创建hash对象
# hashlib.算法名()
hash = hashlib.md5()

# 2.添加数据
# hash对象.update(二进制数据)
pw = '123456'
hash.update(pw.encode())
# hash.update('abc'.encode())

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

# 3.获取摘要
result = hash.hexdigest()
print(result)

3)python二进制数据类型 - bytes

字符串和bytes的相互转换

  1. str -> bytes
    方法一:bytes(字符串, ‘utf-8’)
    方法二:b’字符集’
    方法三:字符串.encode()

  2. bytes -> str
    方法一:str(二进制数据, ‘utf-8’)
    方法二:二进制.decode()

# 字符串转二进制
print(bytes('abc', 'utf-8'))

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

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

# 二进制转字符串
print(str(b1, 'utf-8'))
print(b1.decode())

4)数据的存储

程序中保存的数据默认都是存储在运行内容中,运行内存中的数据在程序结束的时候都会被释放。
如果希望程序运行过程中产生的数据在程序结束后不被销毁,就需要将数据存储到磁盘中。

将数据存储到磁盘过程叫做数据本地化。
数据本地化的基本原理 - 将数据通过文件存储到磁盘中。

5)文件操作(操作文件内容)

文件操作主要解决两个问题:a.怎么将程序中的数据通过文件存储到磁盘中

​ b.怎么在程序中使用保存在文件中的数据

6)文件操作基本步骤

第一步:打开文件
open(文件路径, 读写模式, encoding=文件编码方式) - 以指定方式打开指定文件,返回文件对象
① 文件路径 - 文件在计算机中的位置信息, 以字符串的形式提供值。
a. 绝对路径:文件在计算机中的全路径
b. 相对路径:. - 表示当前目录(当前代码文件所在的目录), ./可以省略
… - 表示当前目录的上层目录
② 读写模式 - 设置打开文件后支持的是读操作还是写操作;设置操作数据的类型是字符串还是二进制
第一组值:
r - 只读
w - 只写;先清空原文件
a - 只写;保留原文件内容,在后面追加数据
第二组值:
t - 数据类型是字符串(t可以省略)
b - 数据类型是bytes

     'r' == 'rt' == 'tr'

注意:如果是文本文件可以用t或者b的方式打开,如果是二进制文件只能以b的方式打开

③ encoding - 文件编码方式(打开的编码方式和文件的编码方式必须一致)
以b的方式打开文件的是encoding不能赋值
第二步:读文件、写文件
文件对象.read()
文件对象.write(数据)

第三步:关闭文件
文件对象.close()

# 参数1:路径
open(r'E:\QianFeng\02语言基础\day14-常用系统模块和文件操作\images\test.txt')
open(r'./images/test.txt')
open(r'./test.py')
open('test.py')
open('images/test.txt')
open('../day14-常用系统模块和文件操作/test.py')

# 参数2:读写模式
# 1) r - 只读
# f = open('test.py', 'r')
# f.read()
# # f.write('abc')   # io.UnsupportedOperation: not writable

# 2) w - 只写;会清空原文件
# f = open('test.py', 'w')
# # f.write('abc')
# # f.read()      # io.UnsupportedOperation: not readable

# 3) a - 只写;会保留原文件内容
# f = open('test.py', 'a')
# # f.write('abc')
# # f.read()      # io.UnsupportedOperation: not readable

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

# f = open('test.py', 'at')
# f.write('abc')

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

f = open('test.py', 'ab')
f.write('abc'.encode())

f.close()
# f.write('abbs'.encode())      # ValueError: write to closed file


1.读操作
"""
1)
文件对象.read()   -   从读写位置开始读到文件结尾(读写位置默认在文件开头)
文件对象.readline()     -   从读写位置开始读到一行的结尾(只有在读文本文件的时候有效)
文件对象.readlines()    -   一行一行的读,读完

2) 

"""
f = open('test.py', encoding='utf-8')
result = f.read()
print(result)

print('-------------------------华丽的分隔线-------------------------------')
f.seek(0)    # 设置读写位置到文件开头
print(f.read())

print('-------------------------华丽的分隔线-------------------------------')
f.seek(0)
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
print('===:', f.readline(), '====', sep='')

print('-------------------------华丽的分隔线-------------------------------')
f.seek(0)
print(f.readlines())
f.close()

print('-------------------------华丽的分隔线-------------------------------')
f = open('test.py', 'a', encoding='utf-8')
f.write('\nabc\n123\n456')
# f.writelines(['abc', '123', '456'])
f.close()

4.数据持久化的基本步骤

第一步:确定需要持久化的数据(确定哪个数据在下一次运行程序的时候还要用)
第二步:创建文件保存数据初始值
第三步:在程序中需要这个数据的时候从文件中读数据
第四步:如果数据发生改变,要将最新的数据写回文件中

# 练习1:写一程序打印程序运行次数
"""
第1次运行程序打印: 1
第2次运行程序打印: 2
第3次运行程序打印: 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))

# 练习2:添加学生,并且在添加完成后显示所有学生信息(只需要学生名字)
"""
请输入学生姓名: 小明
小明   ['小明']

请输入学生姓名:小花
小明 小花   ['小明', '小花']

请输入学生姓名:q
(程序结束)

请输入学生姓名: 张三
小明 小花 张三   ['小明', '小花', '张三']

请输入学生姓名: 李四
小明 小花 张三 李四    ['小明', '小花', '张三', '李四'] 

请输入学生姓名:q
(程序结束)
"""
# 需求1:
# while True:
#     name = input('请输入学生姓名:')
#     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())

# 需求2:
while True:
    name = input('请输入学生姓名:')
    if name == 'q':
        break

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

    f = open('students2.txt', 'w', encoding='utf-8')
    f.write(str(all_student))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值