簡體   English   中英

我的信息不會寫入文件嗎? -Python

[英]My information won't write to a file? - Python

我對Python還是很陌生,我在學校學習它,而我一直在家里弄亂它,我想更好地學習它,以便在GCSE受到熱烈歡迎時才變得更容易。

我的以下代碼有問題:

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

當我輸入'Yes'進入writeinfo()定義時,即使在takeinfo()定義中輸入了某些內容后,它也沒有寫入我要詢問的信息,因為它尚未分配? 任何幫助,將不勝感激。 我知道這很簡單,但是我看了其他問題,但似乎找不到我的代碼有什么問題。

謝謝。

您將需要像這樣傳遞參數:

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

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)

其他答案顯示出良好的功能風格(將information傳遞給writeinfo()函數)

為了完整性,您可以使用全局變量。

您面臨的問題是,生產線

information=input()

(在takeinfo() )會將輸入分配給局部變量,該局部變量takeinfo()同名的全局變量。

為了將其強制為全局變量,您必須使用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來檢查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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM