Python编写的Minecraft挑战轮盘代码无法写入文件问题咨询
Minecraft挑战轮盘日志写入失败修复方案
问题根因
- 你使用了死循环
while(True)没有设置退出路径,Python的文件写入默认会先把内容放到内存缓冲区,只有程序正常退出、缓冲区满、或者手动调用flush操作的时候才会把内容真正写入磁盘。如果你运行过程中直接强制关闭程序,缓冲区的内容会直接丢失,自然看不到写入的日志。 getdate函数重复定义在循环内部,属于不必要的冗余代码,还重复导入了datetime模块- 时间格式化的写法多余,转成列表再转字符串会导致日志时间前后多带方括号,可读性差
修复后代码
import random import datetime # 把日期函数移到循环外,只定义一次 def getdate(): return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') while True: # 获取用户输入,新增退出选项 userInput = int(input("What do you want to do: \n 1) Spin minecraft Challenge Wheel \n 2) Spin Pro Challenge Wheel \n 3) Retrieve Data \n 4) Exit \n Write there serial number to choose: \n")) if userInput == 4: break elif userInput==1: minecraftchallengewheel = ["Do nothing", "Kill ender dragon in 1 minute in any gamemode", "download herobrine mod", "delete your favorite world", "Kill wither in 1 minute", "Be friend of wither"] minecraftchallengechoice = random.choice(minecraftchallengewheel) print(f"You have to {minecraftchallengechoice}") minecraftchallengeyn = input("Do you want to log the data? (y/n) \n") if minecraftchallengeyn == "y": with open("challengelog.txt", "a", encoding="utf-8") as f: f.write(f"{getdate()}: {minecraftchallengechoice}\n") # 手动强制刷入磁盘,避免缓冲区滞留问题 f.flush() # 可在此补充另外两个选项的业务逻辑 elif userInput == 2 or userInput ==3: print("待开发功能")
验证方式
运行程序选择1抽奖,选y记录日志后,选择4正常退出程序,再打开challengelog.txt就能看到写入的日志内容了。
内容的提问来源于stack exchange,提问作者Aditya
相关产品推荐
相关产品推荐

