在编程中,我们可以使用不同的方式来保存文件中的数据。下面是几种常见的解决方法,并附带一些代码示例:
# 写入数据到文件
with open('data.txt', 'w') as file:
file.write('Hello, World!')
# 从文件中读取数据
with open('data.txt', 'r') as file:
data = file.read()
print(data)
import csv
# 写入数据到CSV文件
data = [['Name', 'Age'], ['John', '25'], ['Alice', '30']]
with open('data.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
# 从CSV文件中读取数据
with open('data.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
import json
# 写入数据到JSON文件
data = {
'name': 'John',
'age': 25
}
with open('data.json', 'w') as file:
json.dump(data, file)
# 从JSON文件中读取数据
with open('data.json', 'r') as file:
data = json.load(file)
print(data)
import sqlite3
# 连接到SQLite数据库
conn = sqlite3.connect('data.db')
# 创建数据表
conn.execute('''CREATE TABLE IF NOT EXISTS users
(id INT PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
age INT NOT NULL);''')
# 插入数据
conn.execute("INSERT INTO users (id, name, age) VALUES (1, 'John', 25)")
# 查询数据
cursor = conn.execute("SELECT id, name, age from users")
for row in cursor:
print(row)
# 关闭数据库连接
conn.close()
这些只是一些常见的解决方法,具体的选择取决于你的需求和使用场景。
上一篇:保存文件在应用程序的主目录中