python - 不写入文件
问题描述
我已经编写了这段代码,但它没有在文件中写入数据。
import random
import datetime
while(True):
def getdate():
import datetime
return datetime.datetime.now()
#will take input from the user
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 Write there serial number to choose: \n"))
if 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)
minecraftchallengechoicelist = minecraftchallengechoice
print(f"You have to {minecraftchallengechoice}")
print("Do you want to log the data? (y/n) \n")
minecraftchallengeyn = input()
if minecraftchallengeyn == "y":
with open("challengelog.txt", "a") as f:
f.write(str([str(getdate())]) + ": " + minecraftchallengechoicelist + "\n")
解决方案
这段代码在这里工作。
import random
import datetime
def getdate():
return datetime.datetime.now()
while(True):
#will take input from the user
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 Write there serial number to choose: \n"))
if 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)
minecraftchallengechoicelist = minecraftchallengechoice
print(f"You have to {minecraftchallengechoice}")
print("Do you want to log the data? (y/n) \n")
minecraftchallengeyn = input()
if minecraftchallengeyn == "y":
try:
with open("challengelog.txt", "a") as f:
f.write(str([str(getdate())]) + ": " + minecraftchallengechoicelist + "\n")
except IOError:
print('Fail to open the file')
挑战日志.txt 文件。
['2021-08-23 11:55:54.880117']: Kill ender dragon in 1 minute in any gamemode
['2021-08-23 11:56:39.066004']: Kill ender dragon in 1 minute in any gamemode
['2021-08-23 11:57:02.427010']: download herobrine mod
['2021-08-23 12:01:23.214895']: Be friend of wither
推荐阅读
- python - 您如何将语料库中的所有单词包含在 Gensim TF-IDF 中?
- c++ - 在 C++ 中输出错误数字的数组
- reactjs - 数据存储更改时组件如何更新
- postgresql - PostgreSQL 表布局和索引性能
- java - 如何在 Java 中更新控制台上的输出?(右手规则迷宫求解器)
- javascript - ApostropheCMS:当实际上有孩子时,如何在撇号页面下填充 _children 键?
- qt - QML:ListView 中的鼠标滚轮事件传播
- apache-spark - 使用 PySpark 进行动态时间分析
- python - 放大鼠标位置 QGraphicsView
- python - 如何制作具有跨列一致网格的分组条形图?