系统模块和文件操作

本文详细介绍了Python中的time和datetime模块,包括获取时间戳、本地时间、字符串时间与结构体时间的转换、时间差计算以及文件操作。还探讨了os模块的功能,如获取当前目录、列表目录内容、创建文件夹以及文件路径处理。此外,还讲解了文件操作的基本流程,包括打开、读写和关闭文件。最后,展示了如何进行数据持久化,例如统计程序运行次数。
摘要由CSDN通过智能技术生成

1. time模块

提前导入:

from time import *

1.1 time()

time() - 获取当前时间的时间戳。

1.2 localtime()

localtime() - 获取本地的当前时间,回值是结构体时间。

localtime(时间戳) - 将时间戳转换成本地时间对应的结构体时间。

t1 = localtime()
print(t1)

通过结构体时间获取具体的时间信息:时间对象.时间属性名。

print('年:',t1.tm_year)

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

strptime(字符串时间,时间格式) 。

时间格式 - 包含时间占位符的字符串:

格式含义
%Y
%m
%d
%H时(24小时制)
%I时(12小时制)
%M
%S
%a星期缩写
%A星期全拼
%b月份单词缩写
%B月份单词全拼
%p上午或者下午
t2 = '2002-3-4'
t3 = strptime(t2,'%Y-%m-%d')
print(t3)
print(t3, t3.tm_wday)

t4 = strptime('2022-2-10 9:24:38', '%Y-%m-%d %H:%M:%S')
print(t4)

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

strftime(时间格式,结构体时间)。

t5 = localtime()
# '2022/4/28 9:57:8'
print(f'{t5.tm_year}/{t5.tm_mon}/{t5.tm_mday} {t5.tm_hour}:{t5.tm_min}:{t5.tm_sec}')

result = strftime('%Y/%m/%d %I:%M:%S %p %A %B',t5)
print(result)

1.5 将结构体时间转换成时间戳

mktime(结构体时间)。

t6 = mktime(t5)
print(t6)      # 1651115256.0

1.6 睡眠(等待)

sleep(秒)。

sleep(2)
print('=====end=====')

2. datetime模块

提前导入:

from datetime import datetime,timedelta

2.1 datetime

2.1.1 获取当前时间
t1 = datetime.now()
print(t1,type(t1))    # 2022-04-28 11:14:58.580110 <class 'datetime.datetime'>

t1 = datetime.today()
print(t1)    # 2022-04-28 11:15:28.530466
2.1.2 通过时间值创建时间对象
t1 = datetime(2020, 8, 10)
print(t1)    # 2020-08-10 00:00:00

t2 = datetime(2019, 10, 23, 9, 10)
print(t2)    # 2020-08-10 00:00:00
2.1.3 通过时间对象获取时间值
print(t1.year)    # 2020
print(t1.month)   # 8
print(t1.day)     # 10
print(t1.hour)    # 0
print(t1.minute)  # 0
print(t1.second)  # 0
print(t1.weekday())  # 0 周一
2.1.4 时间对象转字符串时间
result = t2.strftime('%Y年%m月%d日 %a')
print(result)     # '2019年10月23日 Wed'
2.1.5 字符串时间转时间对象
result = datetime.strptime('今天是2022年,3月份,5号','今天是%Y年,%m月份,%d号')
print(result)
2.1.6 将时间对象转换成结构体时间
result = t1.timetuple()
print(result)
2.1.7 获取两个时间的差
t1 = datetime(1998, 2, 20)
t2 = datetime(1998, 1, 7)
result = t1 -  t2        # 时间差
print(result)            # 44 days, 0:00:00
# 基于时间差可以单独获取天数和秒数
print(result.days,result.seconds)

2.2 timedelta

# 2012年3月5日的前10天是哪一天
t1 = datetime(2012,3,5)
print(t1 - timedelta(days=10,hours=0,seconds=0))      # 2012-02-24 00:00:00

# 2022-4-27;五天以后是哪一天
t2 = datetime(2022,4,27)
print(t2 + timedelta(days=5))    # 2022-05-02 00:00:00

# 2022-4-27;五天3小时以后是哪一天
t2 = datetime(2022,4,27)
print(t2 + timedelta(days=5,hours=3))

# 2022-4-27 11:38:20 ;  18个小时前是什么时候
t3 = datetime(2022,4,27,11,38,20)
print(t3 - timedelta(hours=18))    # 2022-04-26 17:38:20

# 2022-4-27 11:38:20 ;  5周前是什么时候
t3 = datetime(2022,4,27,11,38,20)
print(t3 - timedelta(weeks=5))     # 2022-03-23 11:38:20

3. os模块

提前导入:

import os

目录 - 文件夹路径。

3.1 获取当前目录

获取当前目录(获取当前py文件所在的文件夹的路径)。

current = os.getcwd()
print(current)       # E:\zhaoxy\qianfeng\01语言基础\1-代码\day14-系统模块和文件操作

3.2 获取指定目录中所有的内容的名字

os.listdir(文件夹路径)。

3.2.1 路径的写法

1)绝对路径:文件或者文件夹在计算机中的全路径,如果是Windows操作系统,绝对路径从盘开始写;

2)相对路径:

​ 前提:你需要使用的文件或者文件夹必须在当前工程中。

a. 写路径的时候用.表示当前目录(获取当前py文件所在的文件夹的路径)
注意:如果相对路径是’./‘或者’.\‘开头的,’./‘或者’.'可以省略不写
b. 写路径的时候用…表示当前目录的上层目录

result = os.listdir(r'E:\zhaoxy\qianfeng\01语言基础')
print(result)    # ['1-代码', '2-文件-老师', '3-学习总结', '4-作业']


result = os.listdir('./test')
print(result)    # ['aa.py', 'bb.py', '附件01.xlsx']

result = os.listdir('test')
print(result)    # ['aa.py', 'bb.py', '附件01.xlsx']


result = os.listdir('../day14-系统模块和文件操作/test')
print(result)    # ['aa.py', 'bb.py', '附件01.xlsx']

3.3 创建文件夹

3.3.1 mkdir(文件夹路径)

mkdir(文件夹路径) - 在指定位置创建指定文件夹。

# os.mkdir('./新建文件夹1')
# os.mkdir(r'C:\Users\86134\Desktop\新建文件夹\cc')
3.3.2 makedirs(文件夹路径)

makedirs(文件夹路径) - 在指定位置创建指定文件夹(递归创建文件夹,如果路径中有多个文件夹不存在,都会自动创建)。

# os.makedirs('./新建文件夹2')

# os.mkdir('./files/新建文件夹3')    # 报错![WinError 3] 系统找不到指定的路径。: './files/新建文件夹3'
# os.makedirs('./files/新建文件夹3')

3.4 path模块中的函数

3.4.1 获取绝对路径
result = os.path.abspath('.')
print(result)    # 'E:\zhaoxy\qianfeng\01语言基础\1-代码\day14-系统模块和文件操作'
3.4.2 获取文件名

获取文件名:basename(文件路径)。

result = os.path.basename('./test/aa.py')
print(result)    # 'aa.py'
3.4.3 判断文件或者文件夹是否存在

判断文件或者文件夹是否存在:exists(文件路径)。

result = os.path.exists('./test/aa.py')
print(result)    # True

result = os.path.exists('./test/cc.py')
print(result)    # False

result = os.path.exists('./files/新建文件夹3')
print(result)    # True
3.4.4 拼接路径:join(路径1,路径2,…)
result = os.path.join('./files','test','a.txt')
print(result)   # './files\test\a.txt'
3.4.5 将路径切割成文件夹和文件名两个部分
result = os.path.split('./test/aa.py')
print(result)   # ('./test', 'aa.py')
3.4.6 获取文件后缀
result = os.path.splitext('./test/附件01.xlsx')
print(result)   # ('./test/附件01', '.xlsx')

3.5 练习

练习:写一个函数统计指定文件夹中文件和文件夹的数量。

def num_of_file_dir(path):
    """
    统计指定文件夹中文件和文件夹的个数
    :param path: 文件夹路径
    :return: (文件数量,文件夹数量)
    """
    f_num = d_num = 0
    for x in os.listdir(path):
        x_path = os.path.join(path,x)
        print(x_path)
        if os.path.isfile(x_path):
            f_num += 1
        elif os.path.isdir(x_path):
            d_num += 1
    return f'{d_num}个文件夹,{f_num}个文件'


if __name__ == '__main__':
    result = num_of_file_dir('./test')
    print(result)

4. 文件操作

文件操作 - 操作文件内容。

4.1 数据持久化

1)程序中的数据默认保存在运行内存中,保存在运行内存中的数据在程序运行结束后会自动销毁。
如果数据保存在硬盘中,数据会一直存在,直到主动删除或者磁盘损坏!

2)数据持久化 - 指的是以文件为单位将数据保存到硬盘中。(将数据保存到文件中,就是将数据保存到文件中)。

3)问题:a. 怎么将程序中的数据保存到文件中?
b. 怎么将文件中的数据拿到程序中使用?

4.2 文件操作

文件操作基本流程:第一步:打开文件 -> 第二步:操作文件(读操作、写操作)-> 第三步:关闭文件。

4.2.1 打开文件

open(file,mode=‘r’,*,encoding=None) - 以指定方式打开指定文件,返回一个文件对象。

1)a. file - 需要打开的文件的路径;

2)b. mode - 文件打开方式(决定打开文件后能干什么;决定操作文件的时候对应的数据类型)

同时给两组值:

第一组:决定打开后文件能干什么 - 是能读,还是能写
r - 只读(read);
w - 只写(writ e);打开的时候会清空文件
a - 只写(append);打开的时候会保留原文件内容
注意:如果是以读的方式打开一个不存在的文件程序会报错,以写的方式打开不会报错并且会自动创建这个文件

第二组:决定操作数据的类型 - 是字符串(str)还是二进制(bytes)
t - 读写的数据类型必须是字符串(不选,默认就是t)
b - 读写的数据类型必须是二进制
赋值方式:每一组值只能选一个,第一组值必须选,第二组值可以不选,不选就相当于选的t,

​ 例如:‘rt’、‘tr’、’r’、‘rb’、‘a’、…

注意:二进制文件(图片、视频、音频、zip、pdf等)必须以b的方式打开,文本文件t和b都可以

# -------r只读-------
# f = open('./files/students.txt','rt')
# f.read()
# f.write('abc')    # io.UnsupportedOperation: not writable

# ------a只写,保留原文件内容------
# f = open('./files/students.txt','at')
# f.read()          # io.UnsupportedOperation: not readable
# f.write('abc')

# ------w只写,清空原文件内容------
# f = open('./files/students.txt','w')
# f.read()          # io.UnsupportedOperation: not readable
# f.write('abc')

# ------文件不存在的清空------
# 读的方式打开不存在的文件会报错
# open('files/teacher.txt','r')    # 报错!No such file or directory

# 写的方式打开不存在的文件不会报错,并且会自动创建这个文件
# open('files/teacher2.txt','w')
# open('files/teacher3.txt','a')

# 如果是文件夹不存在,写的方式打开还是会报错
# open('files2/teacher3.txt','w')   # No such file or directory

# ------t对应的数据是字符串------
f = open('files/students.txt','rt')
result = f.read()
print(result,type(result))    # abc <class 'str'>
# print(result.upper())         # 'ABC'


f = open('files/students.txt','rb')
result = f.read()
print(result,type(result))    # b'abc' <class 'bytes'>

f = open('files/students.txt','at')
# f.write('hello')    # 报错!write() argument must be str, not list

f = open('files/students.txt','ab')
# f.write('hello')     # 报错!a bytes-like object is required, not 'str'
4.2.2 操作文件

1)读操作 - 文件对象.read()

2)写操作 - 文件对象.write(需要写入文件的数据)

4.2.3 关闭文件

文件操作完成后,必须关闭文件:文件对象.close()。

5. 数据持久化

数据持久化的方法:

第一步:确定需要持久化的数据是什么?

第二步:创建文件,并且确定文件初始内容(分分析需要持久化的数据的初始值);

第三步:在程序中需要这个数据的时候,从文件中去读这个数据;

第四步:当这个数据发生了改变,需要将最新数据写回文件中。

5.1 练习

练习:写入一个程序统计当前程序运行次数。

# 练习:写入一个程序统计当前程序运行次数
# 第一次运行程序:打印1
# 第一次运行程序:打印2
# ...
# 第一步:程序运行次数
# 第二步:初始次数是0 -> 创建run_count.txt保存一个0
# 第三步:
f = open('files/run_count.txt','rt')
count = int(f.read())
f.close()
count += 1
print(count)

# 第四步:
f = open('files/run_count.txt','w')
f.write(str(count))
f.close()

6. 作业

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值