如何将此脚本的输出写入文件

时间:2017-06-05 10:38:40

标签: python-2.7

为您提供特定月份的天数

enter code here
month_name = input("Input the name of Month: ")
if month_name == "February":
   print("No. of days: 28/29 ")
elif month_name in ("April", "June", "September", "November"):
   print("No. of days: 30 ")
elif month_name in ("January", "March", "May", "July", "August", "October", "December"):
   print("No. of days: 31 ")
else:
   print("Wrong month name/write the name of the month with an uppercase at the begining") 

1 个答案:

答案 0 :(得分:0)

你已经标记了这个问题Python-2.7,但它看起来好像你实际上在编写Python 3。

这意味着您的代码存在问题:在Python 2中使用input()时,它希望输入是有效的Python表达式。但是,您并没有告诉用户将其输入括在引号中。如果他们像这样回复你的提示(正如任何合理的用户那样):

Input the name of Month: January

您的程序将因错误NameError: name 'January' is not defined而失败。在Python 2.7中使用raw_input()代替。

同样在Python 2.7中,您需要在程序顶部放置from __future__ import print_function以获得与Python 3相同的行为。我不会为您提供Python 2 print语句语法,因为你的学习没有意义。

要写入文件,请先open,然后将其命名为file来电的print()参数,如下所示:

from __future__ import print_function
with open("myfile.txt","w") as output:
    month_name = raw_input("Input the name of Month: ") # change to input() in Python 3
    if month_name == "February":
       print("No. of days: 28/29 ",file=output)
    elif month_name in ("April", "June", "September", "November"):
       print("No. of days: 30 ",file=output)
    elif month_name in ("January", "March", "May", "July", "August", "October", "December"):
       print("No. of days: 31 ",file=output)
    else:
       print("Wrong month name/write the name of the month with an uppercase at the beginning")

raw_input()外,此代码可在Python 2.7和Python 3.6中使用。