python 处理留言笔记
还记得以前大学时候的学长老大,他让我学习编程,从一个简单的留言本开始尝试学习起来。这么多年过去,现在想学习python,目前从一个留言开始吧。
在Python中处理留言笔记,我们可以使用多种方法,具体取决于你的需求和数据的存储方式。以下是一些常见的方法和步骤:
1. 使用文件存储(文本文件或JSON)
你可以使用Python的内置函数来读取和写入文本文件。
写入留言:
def write_note(filename, note):
with open(filename, 'a', encoding='utf-8') as file:
file.write(note + '\n')
write_note('notes.txt', '这是一条新的留言。')
读取留言:
def read_notes(filename):
with open(filename, 'r', encoding='utf-8') as file:
notes = file.readlines()
return notes
notes = read_notes('notes.txt')
for note in notes:
print(note.strip()) # 使用strip()去除每行末尾的换行符
JSON文件
JSON格式更适合存储结构化数据,例如带有时间戳、用户名的留言。
写入留言:
import json
from datetime import datetime
def write_note_json(filename, note):
data = {'username': '用户名称', 'content': note, 'timestamp': datetime.now().isoformat()}
with open(filename, 'a', encoding='utf-8') as file:
json.dump(data, file)
file.write('\n') # 每个留言后添加换行符以便区分
write_note_json('notes.json', '这是一条新的JSON留言。')
读取留言:
def read_notes_json(filename):
notes = []
with open(filename, 'r', encoding='utf-8') as file:
for line in file:
note = json.loads(line)
notes.append(note)
return notes
notes = read_notes_json('notes.json')
for note in notes:
print(f"用户:{note['username']}, 留言:{note['content']}, 时间:{note['timestamp']}")
2. 使用数据库存储(如SQLite)
对于更复杂的应用,使用数据库(如SQLite)来存储和管理留言是一个好选择。Python的sqlite3库可以方便地处理SQLite数据库。
初始化数据库并创建表:
import sqlite3
conn = sqlite3.connect('notes.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, username TEXT, content TEXT, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP)''')
conn.commit()
conn.close()
写入留言:
import sqlite3
from datetime import datetime
conn = sqlite3.connect('notes.db')
c = conn.cursor()
c.execute("INSERT INTO notes (username, content) VALUES (?, ?)", ('用户名称', '这是一条新的数据库留言。'))
conn.commit()
conn.close()
读取留言:
import sqlite3
conn = sqlite3.connect('notes.db')
c = conn.cursor()
c.execute("SELECT * FROM notes")
rows = c.fetchall()
for row in rows:
print(f"ID: {row[0]}, 用户:{row[1]}, 留言:{row[2]}, 时间:{row[3]}")
conn.close()