Python不会打印到文本文件

时间:2016-03-04 13:32:54

标签: python

由于某种原因,以下代码无法打印到Cache.txt

import random
import time

text_file = open("Cache.txt", "w")
text_file.write("Numbers Used \n")

print("Welcome to the Bingo number generator")
UserNumber = str((random.randint(1,90)))
print(UserNumber)
text_file.write ("UserNumber")
text_file.close

有人可以帮我弄清楚这段代码有什么问题吗?

1 个答案:

答案 0 :(得分:6)

你需要像这样调用close()函数:

text_file.close()

另外,更加pythonic的方式是使用上下文管理器with调用open()

with open("Cache.txt", "w") as text_file:
    text_file.write("Numbers Used \n")
    print("Welcome to the Bingo number generator")
    UserNumber = str((random.randint(1,90)))
    print(UserNumber)
    text_file.write ("UserNumber")

无需以此方式致电close()