如何避免Python心情日记脚本写入时覆盖已有日志内容?
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")withopen("Diary.txt", "a")to append instead of overwrite. - Wrapped the file operations in a
withblock—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

