我的信息不会写入文件? - Python

时间:2017-03-22 21:54:38

标签: python

我对Python很陌生,我在学校学习它并且我在家里一直在搞乱它,我想在GCSE&#时更好地学习它39; s只是为了让它变得更容易。

我遇到以下代码问题:

def takeinfo():
    print("To begin with, would you like to write your file clean? If you're making a new file, yes.")
    choice=input()
    if 'Y' or 'yes' or 'Yes' or 'YES' in choice:
        print("What would you like to write in the file? \n")
        information=input()
        writeinfo()
    else:
        exit()
def writeinfo():
    a=open('names.txt','wt')
    a.write(information)
    a.close()
takeinfo()

当我输入'是'要被写入writeinfo()定义,即使在takeinfo()定义中输入内容之后,它也没有写出要求它的信息,因为它未被分配?任何帮助,将不胜感激。我理解这很简单,但我已经查看了其他问题,而且我似乎无法找到我的代码有什么问题。

三江源。

3 个答案:

答案 0 :(得分:1)

您需要像这样传递参数:

def takeinfo():
    # same as before
    information=input()
    writeinfo(information)
    # else stays the same
def writeinfo(information):
    # rest remains the same...
takeinfo()

或者只是使用global将信息更改为全局范围。

给你一个暗示:

if 'Y' or 'yes' or 'Yes' or 'YES' in choice:

不会像你预期的那样奏效。即使用户输入“否”,您也可以进行一些广泛的学习,找出为什么它总是True

答案 1 :(得分:1)

def writeinfo():
    a=open('names.txt','wt')
    a.write(information)
    a.close()

"信息"需要传递到writeinfo函数

应该是:

def writeinfo(information):
    a=open('names.txt','wt')

及以上,当调用该函数时:

print("What would you like to write in the file? \n")
information=input()
writeinfo(information)

答案 2 :(得分:0)

其他答案显示出良好的功能风格(将information传递给writeinfo()功能)

为了完整起见,你可以也使用全局变量。

你面临的问题是,该行

information=input()

(在takeinfo()中)会将输入分配给 local 变量,该变量会隐藏同名的全局变量。

为了强制它使用全局变量,您必须使用global关键字明确标记它。

其他问题

input vs raw_input

python3中的

input()只会要求您输入一些数据。 但是,在Python2中,它将评估用户数据。因此,在py2上,您应该使用raw_input()

用户是否选择了“是”?

评估choice时是否存在另一个问题(是否写入文件)。 术语'Y' or 'yes' or 'Yes' or 'YES' in choice始终求值为true,因为它实际上被解释为('Y') or ('yes') or ('Yes') or ('YES' in choice),而bool('Y')True。 相反,您应该使用choice in ['Y', 'yes', 'Yes', 'YES']来检查choice是否是列表中的项目之一。 您可以通过规范用户答案来进一步简化此操作(例如,将其封装,删除尾随空格)。

溶液

try:
    input = raw_input
except NameError:
    # py3 doesn't know raw_input
    pass

# global variable (ick!) with the data
information=""

def writeinfo():
    a=open('names.txt','wt')
    a.write(information)
    a.close()

def takeinfo():
    print("To begin with, would you like to write your file clean? If you're making a new file, yes.")
    choice=input()
    if choice.lower().strip() in ['y', 'yes']:
        print("What would you like to write in the file? \n")
        global information
        information=input()
        writeinfo()
    else:
        exit()