初识python之包与内置模块

课堂笔记:

一、常用模块(内置模块)

1、time
# import time # 导入time模块
# # 获取时间戳
# print(time.time())
#
# # 等待2秒
# time.sleep(2)
#
# print(time.time())

2、 os
import os
# 与操作系统中的文件进行交互
# 判断tank.txt文件是否存在
# print(os.path.exists('tank.txt')) # True
# print(os.path.exists('tank1.txt')) # False
# print(os.path.exists(r'D:\python_files\day03\tank.txt')) # True
#
# # 获取当前文件的根目录
# print(os.path.dirname(__file__)) # D:/python_files/day03

3、 sys
import sys
# 获取python在环境变量中的文件路径
# print(sys.path)
# # 把项目的根目录添加到环境变量中
# sys.path.append(os.path.dirname(__file__))
# print(sys.path)


4、 json
import json
# user_info = {
# 'name': 'tank',
# 'pwd': '123'
# }

5、 dumps: 序列化
# 1、把字典转行成json数据
# 2、再把json数据转换成字符串
# res = json.dumps(user_info)
# print(res)
# print(type(res))
#
# with open('user.json', 'wt', encoding='utf-8') as f:
# f.write(res)

6、 loads: 反序列化
# json.loads()
# 1、把json文件的数据读到内存中
# with open('user.json', 'r', encoding='utf-8') as f:
# # 读取得到的是字符串
# res = f.read()
# # print(type(res))
# # loads把json格式的字符串转换成dict类型
# user_dict = json.loads(res)
# print(user_dict) # {'name': 'tank', 'pwd': '123'}
# print(type(user_dict)) # <class 'dict'>


7、dump
# user_info = {
# 'name': 'tank',
# 'pwd': '123'
# }
# with open('user_info.json', 'w', encoding='utf-8') as f:
# # str1 = json.dumps(user_info)
# # f.write(str1)
# # dump: 自动触发f.write方法
# json.dump(user_info, f)


8、load
with open('user_info.json', 'r', encoding='utf-8') as f:
# res = f.read()
# user_dict = json.loads(res)
# print(user_dict)

# load:自动触发f.read()
user_dict = json.load(f)
print(user_dict)


转载于:https://www.cnblogs.com/lweiser/p/11020507.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值