【第15天】Python第一阶段学习总结
2021/10/09
一. 时间模块(datetime)
import time as tm
from datetime import datetime, time, date, timedelta
1. datetime
-
获取当前时间
t1 = datetime.now() print(t1, type(t1)) # 2021-10-09 09:44:49.753901 t11 = datetime.today() print(t11) # 2021-10-09 09:46:31.790271
-
创建datetime对象(时间对象)
t2 = datetime(2002, 10, 1, 21, 30, 5) print(t2) # 2002-10-01 21:30:05 t3 = datetime(2012, 9, 3, minute=30) print(t3) # 2012-09-03 00:30:00
-
单独获取时间数据
print(t3.year) print(t3.month) print(t3.day) print(t3.hour) print(t3.minute) print(t3.second) print(t3.weekday())
-
时间对象和字符串时间的转换
datetime.strptime(字符串时间,时间格式):将字符串时间转换成时间对象
t4_str = '2001_8_3 11:32:40' t4 = datetime.strptime(t4_str, '%Y_%m_%d %H:%M:%S') print(t4, t4.weekday()) # 2001-08-03 11:32:40 4(周五) t5_str = '2020/10/3 10:34:09' t5 = datetime.strptime(t5_str, '%Y/%m/%d %H:%M:%S') print(t5) # 2020-10-03 10:34:09 t6 = tm.strptime(t4_str, '%Y_%m_%d %H:%M:%S') print(t6) # time.struct_time(tm_year=2001, tm_mon=8, tm_mday=3, tm_hour=11, tm_min=32, tm_sec=40, tm_wday=4, tm_yday=215, tm_isdst=-1)
-
将时间对象转换成字符串
时间对象.strftime(时间格式)
t7 = datetime(2020, 1, 5, 23, 50, 34) print(t7) # 2020-01-05 23:50:34 t7_str = t7.strftime('%Y年%m月%d日 %H时%M分%S秒') print(t7_str) # 2020年01月05日 23时50分34秒 # xx月xx日 星期 t7_str1 = t7.strftime('%m月%d日 %a') print(t7_str1) # 01月05日 Sun # 几月 日 t7_str2 = t7.strftime('%b %d') print(t7_str2) # Jan 05 # 上午 3点 t7_str3 = t7.strftime('%p %I') print(t7_str3) # PM 11
2. timedelta:对时间进行加减操作
t8 = datetime(2020, 12, 31, 23, 59, 10)
print(t8) # 2020-12-31 23:59:10
# 加1天
result = t8 + timedelta(days=1)
print(result) # 2021-01-01 23:59:10
# 加1天零5个小时
result = t8 + timedelta(days=1, hours=5)
print(result) # 2021-01-02 04:59:10
# 25小时之前
result = t8 - timedelta(hours=25)
print(result) # 2020-12-30 22:59:10
# 练习:封装一个函数可以将指定的字符串时间转换成时间戳
# xxxx-xx-xx xx:xx:xx
def time_swift(time_str: str, format='%Y-%m-%d %H:%M:%S'):
"""
将指定的字符串时间转换成时间戳
:param time_str: 字符串时间
:param format: 时间格式,默认能转换的是xxxx-xx-xx xx:xx:xx,如果是其他格式的字符串需要自己给format赋值
:return: 时间戳
"""
import time
struct_time = time.strptime(time_str, format)
return time.mktime(struct_time)
time1 = '2020-10-31 10:30:40'
result = time_swift(time1)
print(result)
二. 文件操作
1. 数据持久化(数据本地化)
- 基本理论
程序中的数据默认是保存在运行内存中的,保存在运行内存中的数据在程序运行结束后会被自动销毁。
保存在硬盘、磁盘中的数据在程序结束后不会销毁。
数据持久化:将数据以文件为单位保存在硬盘中。 - 常见数据持久化的工具
数据库文件(.db、.sqlite)、excel文件、csv文件、plist文件(.plist)、json文件(.json)、txt文件(.txt)
2. 文件操作(操作文件内容)
文件操作基本流程:打开文件 -> 操作文件(读、写) -> 关闭文件
-
打开文件
# open(文件路径,打开方式,encoding=文件编码方式) - 以指定的方式打开指定文件,并且返回一个文件对象
- 文件路径:字符串;用来确定需要打开的是哪个文件
-
绝对路径:文件在计算机中的全路径,windows系统一般以某个盘的名字开头
# 绝对路径 open(r'E:\WHY\Python2106\FirstSection\day15-时间模块和文件操作\files\demo1.txt')
-
相对路径:
- 用.表示当前目录
- 用…表示当前目录的上层目录
# 相对路径 open('./files/demo1.txt') open('../day15-时间模块和文件操作/files/demo1.txt')
-
注:当前目录指的是当前代码文件所在的目录;相对路径中最前面的./可以省略
- 打开方式:字符串;决定打开文件后能读还是能写?决定读写的数据的类型是字符串还是二进制?
1) 第一组值:决定读写的(没选,默认是r)
'r' - 只读; 'w' - 只写;打开的时候会清空原文件内容 'a' - 只写;打开的时候保留原文件内容
2) 第二组值:决定数据类型 (没选,默认是t)
'b' - 二进制r 't' - 字符串(文本)
给开打方式赋值的是需要在两组中每一组选一个组合:rt、rb、br、wb、tw…
注意:如果以读的方式打开不存在的文件,程序会报错!如果以写的方式打开不存在的文件,程序不报错并且会自动创建这个文件
-
encoding - 文本文件的编码方式,常用的值是’utf-8’
如果打开文件的时候设置的编码方式和文件本身的编码方式不一致,就会报编码错误
注意:如果是以带b方式打开的文件,都不能给encoding赋值
# r - 只读 f = open('./files/demo1.txt', 'r') f.read() f.write('abc') # io.UnsupportedOperation: not writable # w - 只写;清空 f = open('./files/demo1.txt', 'w') f.write('hello') f.read() # io.UnsupportedOperation: not readable # a - 只写;保留原文件 f = open('files/demo1.txt', 'a') f.write('123') f.read() # io.UnsupportedOperation: not readable # t - 字符串 f = open('files/demo1.txt', 'rt') result = f.read() print(type(result)) # <class 'str'> f = open('files/demo1.txt', 'wt') f.write('123') # b - 二进制(bytes) f = open('files/demo1.txt', 'rb') result = f.read() print(type(result)) # <class 'bytes'> f = open('files/demo1.txt', 'wb') f.write(b'123') # 文件不存在 open('files/demo2.txt', 'r') # FileNotFoundError: [Errno 2] No such file or directory: 'files/demo2.txt' open('files/demo2.txt', 'w') 创建一个新文件 open('files/demo3.txt', 'a') 创建一个新文件 open('files/demo4.txt', encoding='utf-8')
- 文件路径:字符串;用来确定需要打开的是哪个文件
-
文件读写操作
- 读:获取文件内容
文件对象.read() :从读写位置开始,读到文件结尾(针对所有文件有效)
文件对象.readline() :从读写位置开始,读到一行的结尾(只针对以t方式打开的文本文件) - 写:将内容写入到文件中
文件对象.write(内容) :将指定内容写入到文件中
f = open('files/demo1.txt') result1 = f.read() print(result1) print('---------1--------') f.seek(0) # 将读写位置移到文件开头 result2 = f.read() print(result2) print('---------2--------') f.seek(0) result3 = f.readline() print(result3) result4 = f.readline() print(result4)
# 增 f = open('files/demo1.txt', 'a') f.write('\nddd')
# 插入和修改 f = open('files/demo1.txt') result = f.read() # print(result) lines = result.split('\n') print(lines) # lines.insert(2, '000') 插入一行 # lines[1] = 'AAA' # 修改某一行的内容 # lines.remove(lines[-1]) write_data = '\n'.join(lines) # print(lines) f = open('files/demo1.txt', 'w') f.write(write_data)
- 读:获取文件内容
-
关闭文件
文件对象.close()
f.close() f.write('abc') # ValueError: I/O operation on closed file.
with open(文件路径,打开方式,encoding=编码方式) as 文件对象: 文件上下文(离开文件上下文,文件会被自动关闭)
with open('files/demo1.txt') as f: print(f.read()) # print(f.read()) # ValueError: I/O operation on closed file.
三. 数据持久化的方法
1. 数据持久化的方法
- 第一步:确定需要持久化的数据
- 第二步:创建文件保存数据(确定需要持久化的数据的初始值)
- 第三步:程序中需要数据的时候从文件中读数据
- 第四步:数据如果发生改变,要将最新的数据写入到文件中
# 练习:写程序打印程序执行的次数
with open('files/demo2.txt') as f:
count = int(f.read())
count += 1
print(count)
with open('files/demo2.txt', 'w') as f:
f.write(str(count))
# 练习:完成注册的功能;要求下次运行程序的时候可以看到上一次注册的账号
# 请输入账号:
# 请输入密码:
# 提示注册成功! / 提示注册失败!(如果这个账号之前已经注册过了,就注册失败)
# {账号1:密码1, 账号2:密码2, ....}
username = input('请输入账号:')
password = input('请输入密码:')
all_users = eval(open('files/demo4.txt').read())
if username in all_users:
print('注册失败!')
else:
all_users[username] = password
with open('files/demo4.txt', 'w') as f:
f.write(str(all_users))
print('注册成功!')