计科知识库
  • 文章
  • 专题
  • 文章
  • 登录
  • 注册
计科知识库 计科知识库 3小时前

python 处理留言笔记

python

还记得以前大学时候的学长老大,他让我学习编程,从一个简单的留言本开始尝试学习起来。这么多年过去,现在想学习python,目前从一个留言开始吧。

在Python中处理留言笔记,我们可以使用多种方法,具体取决于你的需求和数据的存储方式。以下是一些常见的方法和步骤:

1. 使用文件存储(文本文件或JSON)

你可以使用Python的内置函数来读取和写入文本文件。

‌写入留言:‌

  1. def write_note(filename, note):
  2. with open(filename, 'a', encoding='utf-8') as file:
  3. file.write(note + '\n')
  4. write_note('notes.txt', '这是一条新的留言。')

读取留言:‌

  1. def read_notes(filename):
  2. with open(filename, 'r', encoding='utf-8') as file:
  3. notes = file.readlines()
  4. return notes
  5. notes = read_notes('notes.txt')
  6. for note in notes:
  7. print(note.strip()) # 使用strip()去除每行末尾的换行符

JSON文件

JSON格式更适合存储结构化数据,例如带有时间戳、用户名的留言。

‌写入留言:‌

  1. import json
  2. from datetime import datetime
  3. def write_note_json(filename, note):
  4. data = {'username': '用户名称', 'content': note, 'timestamp': datetime.now().isoformat()}
  5. with open(filename, 'a', encoding='utf-8') as file:
  6. json.dump(data, file)
  7. file.write('\n') # 每个留言后添加换行符以便区分
  8. write_note_json('notes.json', '这是一条新的JSON留言。')

读取留言:‌

  1. def read_notes_json(filename):
  2. notes = []
  3. with open(filename, 'r', encoding='utf-8') as file:
  4. for line in file:
  5. note = json.loads(line)
  6. notes.append(note)
  7. return notes
  8. notes = read_notes_json('notes.json')
  9. for note in notes:
  10. print(f"用户:{note['username']}, 留言:{note['content']}, 时间:{note['timestamp']}")

2. 使用数据库存储(如SQLite)

对于更复杂的应用,使用数据库(如SQLite)来存储和管理留言是一个好选择。Python的sqlite3库可以方便地处理SQLite数据库。

‌初始化数据库并创建表:‌

  1. import sqlite3
  2. conn = sqlite3.connect('notes.db')
  3. c = conn.cursor()
  4. c.execute('''CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, username TEXT, content TEXT, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP)''')
  5. conn.commit()
  6. conn.close()

写入留言:‌

  1. import sqlite3
  2. from datetime import datetime
  3. conn = sqlite3.connect('notes.db')
  4. c = conn.cursor()
  5. c.execute("INSERT INTO notes (username, content) VALUES (?, ?)", ('用户名称', '这是一条新的数据库留言。'))
  6. conn.commit()
  7. conn.close()

读取留言:‌

  1. import sqlite3
  2. conn = sqlite3.connect('notes.db')
  3. c = conn.cursor()
  4. c.execute("SELECT * FROM notes")
  5. rows = c.fetchall()
  6. for row in rows:
  7. print(f"ID: {row[0]}, 用户:{row[1]}, 留言:{row[2]}, 时间:{row[3]}")
  8. conn.close()
  • © 2025 看分享 计科知识库
  • 建议
  • | 鄂ICP备14016484号-7

    鄂公网安备 42068402000189

    访问微博看分享