我对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 :(得分: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()
编辑:你不需要全局变量来解决这个问题...