首页 > 解决方案 > 不写入文件

问题描述

我已经编写了这段代码,但它没有在文件中写入数据。

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")

标签: python

解决方案


这段代码在这里工作。

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

推荐阅读