首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >选项将屏幕上打印的输出保存为文本文件(Python)。

选项将屏幕上打印的输出保存为文本文件(Python)。
EN

Stack Overflow用户
提问于 2016-12-05 01:21:13
回答 3查看 846关注 0票数 0

要么我没有使用正确的搜索字符串,要么这被深深地隐藏在网络中。我知道我们不应该要求家庭作业的答案,但我不想要密码答案,我想知道在哪里找到它,因为我的GoogleFu是坏的。

分配任务是创建一个程序,该程序将在1到9之间滚动两个6边骰子n时间,n是用户定义的。然后,该程序将显示结果,如果滚动为1-1,则使用"Snake Eyes!",如果滚动为6-6,则显示"Boxcar!"。它还必须处理ValueErrors (就像有人将“3”放在“3”而不是"3"),如果用户选择一个不是整数1-9的数字,则返回一条消息。

太好了,我都明白了。但他也希望它能够询问用户是否想将输出保存到文本文件中。恩。是的,翻阅了这本书,还有我的笔记,他还没提到AT ALL。所以现在我被困住了。有人能给我指明正确的方向吗?或者告诉我具体要寻找什么来寻求帮助?

谢谢!

EN

回答 3

Stack Overflow用户

发布于 2016-12-05 01:25:21

您可以这样做,将最后的输出存储到文本文件中。

代码语言:javascript
复制
def print_text(your_result):    
    with open('results.txt', 'w') as file:
        file.write(your_result)

# Take users input
user_input = input("Do you want to save results? Yes or No")

if(user_input == "Yes"):
    print_text(your_result)

我希望这能帮上忙

票数 0
EN

Stack Overflow用户

发布于 2016-12-05 01:32:25

查看输入函数:

https://docs.python.org/3.6/library/functions.html#input

它将允许您从用户请求输入并将其存储在变量中。

票数 0
EN

Stack Overflow用户

发布于 2016-12-05 02:18:55

不是很漂亮,但我想出了这个:

代码语言:javascript
复制
def print_text():
    with open('results.txt', 'w') as file:
        file.write(str(dice))

loop = True
import random
min = 1
max = 6
dice = []
while loop is True:
    try:
        rolls = int(input("How many times would you like to roll the dice?  Enter a whole number between 1 and 9: "))
    except ValueError:
        print("Invalid option, please try again.")
    else:
        if 1 <= rolls <= 9:
            n = 0
            while n < rolls:
                n = n + 1
                print("Rolling the dice ...")
                print("The values are:")
                dice1 = random.randint(min, max)
                dice2 = random.randint(min, max)
                dice.append(dice1)
                dice.append(dice2)
                print(dice1, dice2)
                diceTotal = dice1 + dice2
                if diceTotal == 2:
                    print("Snake Eyes!")
                elif diceTotal == 12:
                    print("Boxcar!")
        else: print("Invalid option, please try again.")

    saveTxt = input("Would you like to save as a text file?  Y or N: ")
    if saveTxt == "Y" or saveTxt == "y":
        print_text()
        break
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40965779

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档