2016-04-07 2 views
0

私は多少Pythonに慣れていて、テキストファイルに書き込もうとしています。ただし、次のコードでは変数をテキストファイルに書き込まず、空のテキストファイルを作成するだけです。なぜこれが分かっていますか?なぜこのファイルへの書き込みが機能しないのですか?

crop = input("Which crop? ") 
quantity = input("How many? ") 

def appendA(): 
file.write (quantity + ' ') 

def appendB(): 
file.write ('\n') 
file.write (crop + ' ') 
file.write (quantity + ' ') 

file = open ('cropdatabase.txt', 'a+') 

if crop in file: 
appendA() 
else: 
appendB() 
+0

Pythonのバージョンを指定します。 –

+1

Pythonのバージョンは3.5.1です – superato

+1

完了したらファイルを閉じていますか? 'file.close()' – mattvivier

答えて

0

簡単な解決策は、グローバル変数を使用する必要があります。ファイルを閉じます。

crop = input("Which crop? ") 
quantity = input("How many? ") 

def appendA(): 
file.write (quantity + ' ') 

def appendB(): 
file.write ('\n') 
file.write (crop + ' ') 
file.write (quantity + ' ') 

file = open ('cropdatabase.txt', 'a+') 

if crop in file: 
appendA() 
else: 
appendB() 
file.close() 

EDIT:あなたはこの私のミスのためにグローバル変数を必要としない...

関連する問題