Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 如何将此脚本的输出写入文件_Python 2.7 - Fatal编程技术网

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

Python 2.7 如何将此脚本的输出写入文件,python-2.7,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 ("Ja

提供特定月份的天数

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

您已经将这个问题标记为Python-2.7,但在我看来,您实际上是在编写Python 3

这意味着您的代码有一个问题:在Python2中使用
input()
时,它希望输入是一个有效的Python表达式。但您并没有告诉用户将他们的输入用引号括起来。如果他们像这样响应您的提示(任何合理的用户都会这样):

您的程序将失败,错误为
name错误:未定义名称“一月”
。在Python2.7中,使用
raw\u input()

同样在Python2.7中,您需要在程序顶部具有来自_uufuture _uuuimport print_函数的
,以获得与Python3相同的行为。我不会向您提供Python2
print
语句语法,因为学习它没有意义

要写入文件,请首先
打开它,然后将其命名为
print()
调用的
file
参数,如下所示:

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\u input()。感谢您回答我的问题,但我仍然有一个问题,您将如何修改您的脚本,以便“天数=任何天数”显示在控制台上。月份的名称会显示在my.file.txt中?
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")