智泊Python–Day11 Day11 转向「标准库实战」——不写业务,而是用 Python 自带模块搞定日常任务。os 管文件系统、json 管数据交换格式、time/datetime 管时间、文件操作 管读写磁盘。这四块是写脚本的刚需:配环境、读配置、记日志、存结果全都用得上。
1.os模块 os 用于和系统打交道、操作文件 / 文件夹。os.mkdir / os.makedirs 建目录(后者建多层),os.remove / os.rmdir 删文件 / 空目录,os.rename 重命名,os.listdir 列目录内容。真正的精华在 os.path 子模块:exists / isdir / isfile 判断存在性与类型,join 拼路径(跨平台安全),split / splitext 拆目录与扩展名,abspath 取绝对路径,getsize 取大小。路径里反斜杠多时,用 r'...' 原始字符串 避免被当成转义。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 import osprint (os.name) print (os.getcwd()) path = r'd:\ZHIBOCODE\test1' print (os.listdir(path))for item in os.listdir(path): print (os.path.join(path, item))print (os.path.split(os.path.join(path, item)))print (os.path.splitext(os.path.join(path, item))) size = os.path.getsize(os.path.join(path, item))print (size)print (os.path.abspath(os.path.join(path, item)))
2.json模块 JSON 是前后端 / 程序间最通用的数据格式。它有两种形态:JSON 字符串 (带引号的文本)和 JSON 对象 (Python 里就是字典)。核心两个函数:
json.loads(字符串):反序列化 ,把 JSON 字符串解析成 Python 字典
json.dumps(字典):序列化 ,把 Python 字典变回 JSON 字符串
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 import json s = '{"name":"邓超","age":18}' d = json.loads(s)print (d)print (type (d)) s2 = json.dumps(d)print (s2)print (s2,type (s2))
3.时间模块 time.time() 返回时间戳 (1970-01-01 00:00:00 到现在的秒数,浮点);time.sleep(n) 让程序暂停 n 秒。datetime 是对 time 的封装,更人性化:datetime(...) 直接构造日期时间对象,对象上有 .year/.month/... 属性;strftime(格式) 把对象转成字符串,strptime(字符串, 格式) 反向解析;timedelta(days=...) 表示时间差,可以直接和日期对象做加减。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 import timeprint (time.time()) time.sleep(1 ) print ('hello world' )print ("=" *20 )import datetime dt = datetime.datetime(year=2023 , month=10 , day=10 , hour=12 , minute=30 , second=0 ) print (dt)print ("=" *20 )print (dt.year) print (dt.month) print (dt.day) print (dt.hour) print (dt.minute) print (dt.second) print (dt.date()) print (dt.time()) print ("=" *20 ) dfstr = dt.strftime('%Y-%m-%d %H:%M:%S' )print (type (dfstr)) print (dfstr) print ("=" *20 ) dt = datetime.datetime.strptime(dfstr, '%Y-%m-%d %H:%M:%S' )print (type (dt)) print (dt) print ("=" *20 ) d1 = datetime.timedelta(days=25 ) addt = dt + d1 delt = dt - d1print (dt) print (addt) print (delt) print (delt.day) print (delt.day // 5 )
4.文件操作 读写文件靠内置 open()。模式要分清:**r 只读(不存在报错)、 w 清空写(不存在则新建)、 a 追加写**(不存在则新建);带 b 的是二进制模式(图片、音视频)。read() 读全部、read(n) 读 n 个字符(第二次调用从上次位置继续)、readline() 读一行、readlines() 读全部成列表。最推荐 with open(...) as f: 写法——离开代码块自动 close(),不怕忘了关文件导致资源泄漏。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 import os f = open ("Python/Python_day11/hello.txt" , "r" , encoding="utf-8" ) print (f.read()) f.close()print ("=" *20 ) f = open ("Python/Python_day11/hello.txt" , "w" , encoding="utf-8" ) f.write("你好,空指针" ) print ("=" *20 ) f.close()with open ("Python/Python_day11/hello.txt" , "r" , encoding="utf-8" ) as f: print (f.read())print ("=" *20 )
5.作业 作业是把 Day10 的「包 / 模块」落进实战:自建一个 test 包,里面 sort.py 提供三个函数——sort1 降序(不改动原列表)、sort2 升序(不改动原列表)、find_index 返回指定元素所有下标组成的列表;再在另一个文件里 from test import sort 调用它们。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 from test import sort l = [1 , 3 , 2 , 4 , 5 ]print (sort.sort1(l))print (sort.sort2(l))print (sort.find_index(l, 2 ))