csv模块
import csv
# data.csv不存在时,会现在当前目录下创建一个data.csv文件
with open("data.csv", "w", encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(["trasanction_id", "product_id", "price_id"])
writer.writerow([1000, 1, 50])
writer.writerow([1001, 5, 153])
writer.writerow([1002, 16, 210])
with open("data.csv") as file:
reader = csv.reader(file)
print(list(reader))
json模块
json.dumps():可以将一个Python对象(如字典、列表、字符串、数字等)作为参数传递给该函数,它一个JSON格式的字符串。
import json
from pathlib import Path
# 创建一个Python字典
data = {
'name': 'John Doe',
'age': 30,
'is_student': False,
'courses': ['Math', 'Science']
}
# 将字典转换为JSON格式的字符串
json_str = json.dumps(data)
# 打印JSON字符串
print(json_str)
# 在当前目录创建一个json文件,把json_str写到该文件中
Path("data.json").write_text(json_str, encoding='utf-8')
# 读json文件
data_read = Path("data.json").read_text(encoding='utf-8')
print(data_read)
print(type(data_read)) # Path.read_text()返回的是一个str对象
data_dict = json.loads(data_read) # 返回一个 字典对象 或者 字典array
print(type(data_dict)) # <class 'dict'>
print(data_dict)
sqlite3模块
- sqlite3 模块是 Python 标准库的一部分,它提供了一个接口,允许 Python 程序与 SQLite 数据库进行交互。
-
SQLite是轻量级的嵌入式数据库,无需独立服务器进程(不用独占服务器的资源),适合单用户或低并发场景;
-
SQLite功能相对简单,不支持存储过程、触发器等高级特性,数据安全性较低;
-
SQLite适用于嵌入式设备、移动应用和轻量级桌面应用
-
DB Browser for SQLite 是一款开源的图形界面数据库管理工具
-
DB Browser SQLite内置了SQLite,故只需要安装DB Browser SQLite详见:https://www.cnblogs.com/kakafa/p/18374746
新建一个json文件:
import sqlite3
import json
from pathlib import Path
# 返回一个数据类型为字典的array
stus = json.loads(Path("student.json").read_text(encoding='utf-8'))
print(stus)
# 如果db.sqlite3文件不存在 会自动创建
with sqlite3.connect("db.sqlite3") as conn: # 会返回一个Connection对象
command = "INSERT INTO Students VALUES(?,?,?)" # Students表需要提前建立好(创建表后记得保存),否则报错
for stu in stus:
conn.execute(command, tuple(stu.values()))
conn.commit()
# 查找
with sqlite3.connect("db.sqlite3") as conn:
command = "SELECT * FROM Students"
cursor = conn.execute(command)
for row in cursor:
print(row)
# conn.commit() 读数据时不需要提交,涉及到写修改才需要提交
还可以转换成元组输出:
with sqlite3.connect("db.sqlite3") as conn:
command = "SELECT * FROM Students"
cursor = conn.execute(command)
tuple_stu = cursor.fetchall()
print(tuple_stu)
datetime模块
from datetime import datetime
import time
dt = datetime(2020, 1, 1)
print(dt)
current_dt = datetime.now()
print(current_dt)
# strptime()用于将字符串形式的日期和时间解析为datetime对象
time_s = datetime.strptime("1980/01/20", "%Y/%m/%d") # 注意 大小写不一样 格式也不一样
print(time_s)
# 把timestamp会转换成datetime的形式
time_d = datetime.fromtimestamp(time.time())
print(time_d)
from datetime import datetime, timedelta
import time
dt1 = datetime(2020, 1, 1)
dt2 = datetime.now() # 2024-08-22
duration = dt2-dt1
print(duration) # 1695 days, 22:08:38.756208
print(duration.days) # 1695
print(duration.seconds) # 79718
# timedelta
dt3 = datetime(2020, 1, 1)+timedelta(days=1, seconds=20) # 增加1天20秒
print(dt3) # 2020-01-02 00:00:20
标签:05,python,datetime,sqlite3,json,print,import,data From: https://www.cnblogs.com/kakafa/p/18374864