You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何避免Python心情日记脚本写入时覆盖已有日志内容?

Fixing Your Mood Diary's Overwrite Problem

Hey there! The issue here is how you're opening your diary file—using the w (write) mode tells Python to erase any existing content in the file before writing new stuff. That's why each new entry replaces the old one.

The Fix: Use Append Mode

Instead of w, use the a (append) mode when opening the file. This will add new entries to the end of the existing file instead of overwriting it.

Even better, let's use a with statement (context manager) to handle the file—this is cleaner because it automatically closes the file for you, so you don't have to remember to call text_file.close() manually.

Here's the updated code:

import datetime

date = datetime.datetime.now()
print('My Mood Diary:')
mood = input('How are you feeling today? ')

# Use "a" mode to append, and with statement for safe file handling
with open("Diary.txt", "a") as text_file:
    # Add a separator between entries for readability
    text_file.write('\n' + '-'*30 + '\n')
    text_file.write('Date:\n')
    text_file.write(date.strftime("%Y-%m-%d @ %H:%M:%S\nEntry:\n"))
    text_file.write(mood)
    text_file.write('\n')

What Changed?

  • Replaced open("Diary.txt", "w") with open("Diary.txt", "a") to append instead of overwrite.
  • Wrapped the file operations in a with block—this ensures the file is properly closed even if something goes wrong.
  • Added a separator line (---...---) between entries to make the diary easier to read when you open it later.

Now every time you run the script, your new mood entry will be added right after the previous ones instead of replacing them.

内容的提问来源于stack exchange,提问作者Ruukasu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 18:32:35