简体   繁体   English

为什么写此文件不起作用?

[英]Why doesn't this writing to file work?

I am somewhat new to python and am trying to write to a text file. 我是python的新手,正在尝试写入文本文件。 However, the following code doesn't write the variables to the text file, it just creates an empty text file. 但是,以下代码不会将变量写入文本文件,而只是创建一个空的文本文件。 Does any know why this is? 有谁知道这是为什么吗?

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

Easy solution you need to be using global variables. 您需要使用全局变量的简单解决方案。 And close the file. 并关闭文件。

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: You don't need global variables for this my mistake... 编辑:您不需要全局变量为此我的错误...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM