day15-时间模块和文件操作

day15-时间模块和文件操作(10.9)

1、review

# 1.装饰器
"""
def 装饰器名(原函数):
    def 新函数(*args,**kwargs):
        result = 原函数(*args,**kwargs)
        新增功能
        return result
    return 新函数
"""

# 2.模块和包
import time

"""
import 模块  (模块.)
from 模块 import 变量1,变量2,。。。
from 模块 import *
import 模块 as 新模块
from 模块 import 变量1 as 新变量1,变量2,。。。

import 包名
import 包名.模块名(as 重命名)
from 包 import 模块
from 包.模块 import 变量1,变量2,...
"""
# from text import test1
# if __name__ = __main__():  快捷方式
#     pass

# 3.time模块
# 1)time.time()- 获取当前时间的时间戳
# 2)time.localtime() - 获取当前本地时间,返回结构体时间
# time.localtime(时间戳) - 将时间戳转换成本地的结构体时间
time.localtime()

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

2、时间模块

1.datetime

1)获取当前时间

# import datetime
import time as tm
from datetime import datetime, time, date, timedelta    # 年月日时分秒微秒,时分秒,年月日,时间差时间加减运算(时分秒天)
t1 = datatime.now()
print(t1, type(t1)) # 2021-10-09 09:42:09.324367 <class 'datetime.datetime'>
t11 =datetime.today()
print(t11) # 2021-10-09 09:46:42.052896
  1. 创建datetime对象(时间对象)
t2 = datetime(2002, 10, 1)
print(t2)  # 2002-10-01 00:00:00
t3 = datetime(2012, 9, 3, minute = 30)
print(t3) # 2012-09-03 00:30:00 关键字参数传参,其他默认为0

3)单独获取时间数据(年月日时分秒)

print(t2.year)  # 年
print(t2.month)  # 月
print(t2.day)   # 日
print(t2.hour)  # 时
print(t2.minute)  # 分
print(t2.second)  # 秒
print(t3.weekday())  # 星期  0->周一

4)时间对象和字符串时间的转换

将字符串时间换行成时间对象:datetime.strptime(字符串时间,时间格式)

t4_str = '2001-8-3 11:32:40'
t4 = datetime.strptime(t4_str, '%Y-%m-%d %H:%M:%S')
# tm.strptime()
print(t4, t4.weekday()) # 2001-08-03 11:32:40 4

t5_str = '2001/8/3 11:32:40'
t5 = datetime.strptime(t5_str, '%Y/%m/%d %H:%M:%S')
print(t5, t5.hour)  # 2001-08-03 11:32:40 11

t6 = tm.strptime(t4_str, '%Y-%m-%d %H:%M:%S') # 结构体时间,可以转换为时间戳 tm是重新命名的time
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)

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

时间对象.strftime(时间格式)

ctrl + 长按进去的详细用法

#     %Y  Year with century as a decimal number.
#     %m  Month as a decimal number [01,12].
#     %d  Day of the month as a decimal number [01,31].
#     %H  Hour (24-hour clock) as a decimal number [00,23].
#     %M  Minute as a decimal number [00,59].
#     %S  Second as a decimal number [00,61].
#     %z  Time zone offset from UTC.
#     %a  Locale's abbreviated weekday name.
#     %A  Locale's full weekday name.
#     %b  Locale's abbreviated month name.
#     %B  Locale's full month name.
#     %c  Locale's appropriate date and time representation.
#     %I  Hour (12-hour clock) as a decimal number [01,12].
#     %p  Locale's equivalent of either AM or PM.
t7 = datetime(2020, 1, 5, 23, 50, 34)
print(t7, type(t7))  #时间对象 2020-01-05 23:50:34  <class 'datetime.datetime'>

xxxx年xx月xx日 xx时xx分xx秒

t7_str = t7.strftime('%Y年%m月%d日 %H时%M分%S秒')
print(t7_str)     # 2020年01月05日 23时50分34秒

xx月xx日 星期

t7_str = t7.strftime('%m月%d日 %a')
print(t7_str)    # 01月05日 Sun

几月 日

t7_str = t7.strftime('%b %d')
print(t7_str)     # Jan 05

上午 3点

t7_str = t7.strftime('%p %I')
print(t7_str) # PM 11

2.timedelta - 对世界进行加减操作的

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) # ctrl+ 点进查看
print(result) # 2020-12-30 22:59:10 # 结果依旧是时间对象
# 练习:封装一个函数可以将指定的字符串时间转换成时间戳
# xxxx-xx-xx xx:xx:xx
# str1 = '2020-12-12 12:12:12'
# t1 = tm.strptime(str1,'%Y-%m-%d %H:%M:%S')
# t2 = tm.mktime(t1)
# print(t2)

# 自己练习
# def shijianchuo(str1):
#     t1 = tm.strptime(str1, '%Y-%m-%d %H:%M:%S')
#     t2 = tm.mktime(t1)
#     return t2
# str1 = '2020-12-12 12:12:12'
# print(shijianchuo(str1))

# teacher正确答案
def get_timestamp(t:str, format='%Y-%m-%d %H:%M:%S'): # 自己提供格式
    """
    将字符串时间转换成时间戳
    :param t: 字符串时间
    :param format: 时间格式,默认能转换的是xxxx-xx-xx xx:xx:xx,如果是其他格式的字符串需要自己给format赋值
    :return:时间戳
    """
    import time # 内部导入time
    # struct_t = time.strptime(t, '%Y-%m-%d %H:%M:%S') #将字符串时间转换成结构体时间,根据格式调整
    struct_t = time.strptime(t, format) #将字符串时间转换成结构体时间,根据格式调整
    return time.mktime(struct_t) # 将结构体时间转换成时间戳

print(get_timestamp('2020-12-12 12:12:12')) # 1607746332.0

3、文件操作

1.数据持久化(数据本地化)

“”"

  1. 基本理论
    程序中的数据默认是保存在运行内存中的,保存在运行内存中的数据在程序运行结束后会被自动销毁。
    保存在硬盘,磁盘中的数据在程序结束后不会销毁,会一直存在。
    数据持久化 - 将数据以文件为单位保存在硬盘中。

  2. 常见数据持久化的工具
    数据库文件(.db,.sqlite)、excel文件、csv文件、txt文件(.txt)、plist文件(.plist)、json文件(.json)

“”"

2.文件操作(操作文件内容)

文件操作基本流程:打开文件 -> 操作文件(读,写)改动就是写 -> 关闭文件

  1. 打开文件
    “”"
    open(文件路径,打开方式=‘r’,encodings = 文件编码方式) - 以指定的方式打开指定文件,并且返回一个文件对象
    a.文件路径 - 字符串;用来确定需要打开的是哪个文件
    绝对路径:文件在计算机中的全路径,windows系统一遍以某个盘的名字开头
    拖拽在命令提示符/直接找到文件路径(写全)

相对路径:1)用.表示当前目录
2)用…表示当前目录的上层目录
注:当前目录指的是当前代码文件所在的目录,相对路径中最前面的./可以省略。

b.打开方式 - 字符串;决定打开文件后能读还是能写?决定读写的数据的类型是字符串还是二进制?
1)第一组值:决定读写的 open
‘r’ - 只读;
‘w’ - 只写;打开的时候会清空原文件内容(再写)
‘a’ - 只写;打开的时候不会清空原文件内容(再写)
2)第二组值:决定数据类型(没选,默认是t)
‘b’ - 二进制
‘t’ - 字符串(文本)
给打开方式赋值的时候需要在两组值中每一组选一个值组合:rt,rb,br,wb,tw…(rb,br顺序不影响)
注意:如果以读的方式打开不存在的文件,程序会报错!如果以写的方式打开不存在的文件,程序不报错并且会自动创建这个文件。(有这个文件夹)
c.encoding - 文本文件的编码方式,常用的值是 ‘utf-8’ (jpk?)
如果打开文件的时候设置的编码方式和文件本身的编码方式不一致,就会报编码错误
注意:如果是以带b的方式打开的文件,都不能给encoding赋值(t才可以)
“”"

# 绝对路径
# open(r'D:\QianFeng\python jichu\day15-时间模块和文件操作\files\demo1.txt')
# # open(r'"D:\QianFeng\python jichu\day15-时间模块和文件操作\files\demo1.txt"')
#
# # 相对路径
# open('./files/demo1.txt') # 相对路径里./可以省略
# open('../day15-时间模块和文件操作/files/demo1.txt')

# ==r - 只读
# f = open('./files/demo1.txt', 'r')
# f.read()   # 文件对象 f
# f.write('abc')  # 报错 io.UnsupportedOperation: not writable
# open('files/demo1.txt')

# == 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('1234')
# f.read() # 报错 io.UnsupportedOperation: not readable

# ==t - 字符串 ==
# f = open('./files/demo1.txt', 'rt')
# result = f.read()
# print(result, type(result)) # hello1234 <class 'str'>

# ==b - 二进制(bytes) ==
# f = open('./files/demo1.txt', 'rb') # 'rb'和'br'一样
# result = f.read()
# print(result, type(result))  # b'hello1234' <class 'bytes'>二进制字节流
#
# f = open('files/demo1.txt', 'wt') # 写入的数据类型由t决定
# f.write('123')
# f = open('files/demo1.txt', 'wb')
# f.write(b'123')
#
# # r,w,,a,t,b
# f = open('files/demo1.txt', 'ab')
# f.write(b'123')
#
# # == 文件不存在 == 默认为'r'
# # open('./files/demo2.txt', 'r')   # 报错 FileNotFoundError
# open('./files/demo2.txt', 'w')    # 会自动创建demo2
# open('./files/demo3.txt', 'a')   #  会自动创建demo3
#
# open('files/tet1.txt',  encoding='utf-8')
  1. 文件读写操作
    “”"
    a. 读 - 获取文件内容
    文件对象.read()(打开文件得到的文件对象) - 从读写位置开始,读到文件结尾(针对所有文件有效)
    文件对象.readline() - 从读写位置开始,读到一行的结尾(只针对以t方式打开的文本有效)

b. 写 - 将内容写入到文件中
文件对象.write(内容) - 将指定内容写入到文件中
“”"

# f = open('files/demo1.txt')
# result1 = f.read()
# print(result1)
#
# result2 = f.read()
# print(result2) # 光标 -> 空
#
# print('-------1----------')
# f.seek(0) # 将读写位置移动到文件开头(重新打开文件)
# result2 = f.read()
# print(result2)
# print('-------2----------')
# f.seek(0) # 将读写位置移动到文件开头(重新打开文件)
# result2 = f.readline()
# print(result2) # 123123
# result3 = f.readline()
# print(result3)

# 增
# f = open('files/demo1.txt', 'a')
# f.write('\nccc')

# 插入和修改
f = open('files/demo1.txt')
# result = f.read()
# lines = result.split('\n')
# # lines.insert(2, '000') # 插入一行
# lines[1] = 'AAA' # 修改某一行的内容
# write_data = '\n'.join(lines)
# f = open('files/demo1.txt', 'w')
# f.write(write_data)
#
# # 删除
# f = open('files/demo1.txt')
# result = f.read()
# lines = result.split('\n')
# # lines[-1] = ''
# del lines[-1] #删除最后一行
# write_data = '\n'.join(lines)
# f = open('files/demo1.txt', 'w')
# f.write(write_data)

3.关闭文件

文件对象.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.

4、数据持久化方法

“”"
1
1+1 =2
2+1 =3
“”"
1.数据持久化的方法
“”"
第一步:确定需要持久化的数据
第二步:创建文件保存数据(确定需要持久化的数据的初始值)
第三步:程序中需要数据的时候从文件中读数据
第四步:数据如果发生改变,要将最新的数据写入到文件中
“”"

# **练习:写程序打印程序执行的次数
# 第一步:次数需要持久化
# count = int(open('files/count.txt').read())
with open('files/count.txt') as f:
    count = int(f.read())
count += 1
print(count)

with open('files/count.txt','w') as f:
    f.write(str(count))
# 打印次数
# 次数加1
# 练习:完成注册的功能;要求下次运行程序的时候可以看到上一次注册的账号
# 请输入账号:
# 请输入密码:
# 提示注册成功!   /  提示注册失败!(如果这个账号之前已经注册过了,就注册失败)
# {账号1:密码1, 账号2:密码2, ....}
# {'abc': '12334'}  -str()-> "{'abc': '12334'}"  -eval()-> {'abc': '12334'}
username = input('请输入账号:')
password = input('请输入密码:')
# 获取所有已经注册过的账号
all_user = eval(open('files/users.txt', 'r').read())   # '{}'
# 判断当前输入的账号是否已经注册过
if username in all_user:
    print('注册失败!')
else:
    all_user[username] = password
    with open('files/users.txt', 'w') as f:
        f.write(str(all_user))
    print('注册成功!')

本次需要结合新建立文档进行学习和练习

abc’: ‘12334’} -str()-> “{‘abc’: ‘12334’}” -eval()-> {‘abc’: ‘12334’}
username = input(‘请输入账号:’)
password = input(‘请输入密码:’)
获取所有已经注册过的账号
all_user = eval(open(‘files/users.txt’, ‘r’).read()) # ‘{}’
判断当前输入的账号是否已经注册过
if username in all_user:
print(‘注册失败!’)
else:
all_user[username] = password
with open(‘files/users.txt’, ‘w’) as f:
f.write(str(all_user))
print(‘注册成功!’)


本次需要结合新建立文档进行学习和练习

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9SQXQwR2-1633779207586)(C:\Users\z\Desktop\tupian\10.91.png)]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值