python--常用内置库
时间模块:处理日期时间
# 时间模块:处理日期时间
def dateTimeMain():
from datetime import datetime
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S")) # 格式化输出: 2024-07-20 14:30:00
print("------------------")
dateTimeMain()
os模块:操作系统交互
# os模块:操作系统交互
def osMain():
import os
print(os.getcwd()) # 获取当前工作目录
print("------------------")
os.mkdir("new_folder") # 创建文件夹
osMain()
json模块:JSON数据处理
# json模块:JSON数据处理
def jsonMain():
import json
data = {"name": "Alice", "age": 25}#键值对对象
print("---------------")
print(data["age"])
json_str = json.dumps(data) # 转为JSON字符串(转换成字符串)
print("---------------")
print(json_str)#打印字符串
loaded_data = json.loads(json_str) # 解析JSON(将字符串转化成json对象)
print("---------------")
print(loaded_data["name"])
jsonMain()
文件与数据处理进阶
# 文件与数据处理进阶
def openJsonFileMain():
import json
data = {"name": "喜羊羊", "age": 25,"sex":"男"}#键值对对象
# 写入JSON文件
with open("data.json", "w",encoding="utf-8") as f:
json.dump(data, f)
# 读取JSON文件
with open("data.json", "r",encoding="utf-8") as f:
dataRead = json.load(f)
print("--------")
print(dataRead["name"])
print(dataRead["age"])
import csv
# 读取CSV并转为字典列表
with open("data.csv", "r",encoding="utf-8") as f:
reader = csv.DictReader(f)
print("--------")
for row in reader:
print(row["Name"], row["Age"])
openJsonFileMain()
异常处理
# 异常处理
def exMain():
class NegativeNumberError(Exception):
pass
def check_positive(num):
if num < 0:
raise NegativeNumberError("数字不能为负数")
print(num)
try:
check_positive(-10)
except NegativeNumberError as e:
print(e) # 输出: 数字不能为负数
exMain()