This commit is contained in:
2025-08-26 17:30:04 +08:00
parent e58a4612ef
commit b411789fd3
12 changed files with 112 additions and 0 deletions

View File

@@ -0,0 +1,14 @@
import csv
# 写入 CSV
with open('data.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(['Name', 'year', 'value']) # 写入表头
writer.writerow(['Guan', 1993, 1])
writer.writerow(['G123', 2025, 0])
# 读取 CSV
with open('data.csv', 'r', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader:
print(row) # 每行是一个列表

View File

@@ -0,0 +1,16 @@
import h5py
import numpy as np
# 写入数据
with h5py.File('data.h5', 'w') as f:
f.create_dataset('array', data=np.random.rand(3, 3))
f.attrs['info'] = '3x3随机矩阵'
# 读取数据
with h5py.File('data.h5', 'r') as f:
array_data = f['array'][:]
info = f.attrs['info']
print('数组数据:')
print(array_data)
print('信息:', info)

View File

@@ -0,0 +1,17 @@
import json
data = {
"name": "Guan",
"year": 1993,
"hobbies": ["coding", "reading"],
}
# 写入
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, indent=4) # indent 使输出格式化,更易读
# 读取
with open('data.json', 'r', encoding='utf-8') as f:
loaded_data = json.load(f)
print(loaded_data)
print(loaded_data['name'])

View File

@@ -0,0 +1,12 @@
import pickle
data = [1, 2, 3]
# 写入
with open('data.pkl', 'wb') as f: # 注意是 'wb' 二进制写入
pickle.dump(data, f)
# 读取
with open('data.pkl', 'rb') as f: # 注意是 'rb' 二进制读取
loaded_data = pickle.load(f)
print(loaded_data)

View File

@@ -0,0 +1,26 @@
import sqlite3
# 1. 连接数据库(自动创建)
conn = sqlite3.connect('data.db')
cursor = conn.cursor()
# 2. 创建表
cursor.execute('CREATE TABLE IF NOT EXISTS users (name TEXT, age INTEGER)')
# 3. 插入数据
cursor.execute("INSERT INTO users VALUES ('张三', 25)")
cursor.execute("INSERT INTO users VALUES ('李四', 30)")
# 4. 提交更改
conn.commit()
# 5. 读取数据
cursor.execute('SELECT * FROM users')
rows = cursor.fetchall()
print("所有用户数据:")
for row in rows:
print(f"姓名: {row[0]}, 年龄: {row[1]}")
# 6. 关闭连接
conn.close()

View File

@@ -0,0 +1,14 @@
# 写入
with open('data.txt', 'w', encoding='utf-8') as f:
f.write('test_1\ntest_2')
# 读取
with open('data.txt', 'r', encoding='utf-8') as f:
content = f.read() # 读取全部内容
print(content)
with open('data.txt', 'r', encoding='utf-8') as f:
lines = f.readlines() # 或按行读取
print(lines)
for line in lines:
print(line.strip()) # strip() 去除首尾空白字符

View File

@@ -0,0 +1,3 @@
Name,year,value
Guan,1993,1
G123,2025,0
1 Name year value
2 Guan 1993 1
3 G123 2025 0

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,8 @@
{
"name": "Guan",
"year": 1993,
"hobbies": [
"coding",
"reading"
]
}

Binary file not shown.

View File

@@ -0,0 +1,2 @@
test_1
test_2