文件存储JSON文件JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。在Python中,可以使用json模块来处理...
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。在Python中,可以使用json模块来处理JSON数据。
import json
# 创建数据
data = { "name": "John", "age": 30, "city": "New York"
}
# 将数据写入JSON文件
with open('data.json', 'w') as json_file: json.dump(data, json_file)
# 从JSON文件读取数据
with open('data.json', 'r') as json_file: data_loaded = json.load(json_file) print(data_loaded)CSV(Comma-Separated Values)是一种简单的文件格式,用于存储表格数据。Python可以使用csv模块来处理CSV数据。
import csv
# 创建数据
data = [ ["name", "age", "city"], ["John", 30, "New York"], ["Jane", 25, "Los Angeles"]
]
# 将数据写入CSV文件
with open('data.csv', 'w', newline='') as csv_file: writer = csv.writer(csv_file) writer.writerows(data)
# 从CSV文件读取数据
with open('data.csv', 'r') as csv_file: reader = csv.reader(csv_file) for row in reader: print(row)MySQL是一种关系型数据库管理系统,Python可以使用mysql-connector-python或pymysql等模块来操作MySQL数据库。
import mysql.connector
# 连接数据库
conn = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword", database="yourdatabase"
)
# 创建游标对象
cursor = conn.cursor()
# 创建表
cursor.execute("CREATE TABLE IF NOT EXISTS users (name VARCHAR(255), age INT, city VARCHAR(255))")
# 插入数据
cursor.execute("INSERT INTO users (name, age, city) VALUES (%s, %s, %s)", ("John", 30, "New York"))
# 查询数据
cursor.execute("SELECT * FROM users")
results = cursor.fetchall()
for row in results: print(row)
# 关闭连接
conn.close()Redis是一种高性能的键值存储系统,Python可以使用redis模块来操作Redis数据库。
import redis
# 连接Redis
r = redis.Redis(host='localhost', port=6379, db=0)
# 设置键值对
r.set('name', 'John')
# 获取键值对
print(r.get('name').decode())MongoDB是一种基于文档的NoSQL数据库,Python可以使用pymongo模块来操作MongoDB数据库。
from pymongo import MongoClient
# 连接MongoDB
client = MongoClient('localhost', 27017)
# 选择数据库
db = client['mydatabase']
# 创建集合
collection = db['users']
# 插入文档
collection.insert_one({"name": "John", "age": 30, "city": "New York"})
# 查询文档
for document in collection.find(): print(document)pandas处理大数据pandas是一个强大的数据分析库,可以轻松处理大型数据集。
import pandas as pd
# 读取CSV文件
df = pd.read_csv('data.csv')
# 处理数据
df['age'] = df['age'] * 2
# 保存数据
df.to_csv('data_processed.csv', index=False)numpy处理数组numpy是一个高性能的科学计算库,可以用于处理大型数组。
import numpy as np
# 创建数组
array = np.array([1, 2, 3, 4, 5])
# 处理数组
result = np.sum(array)
# 打印结果
print(result)通过以上解析,您应该能够更好地理解Python中的数据存储和操作技巧。希望这些信息能帮助您在数据处理和存储方面取得更好的效果。