python - 如何将函数输出转储到 .txt 文件?
问题描述
def example():
print("hello, world!")
times = int(input("how many 'hello worlds'? "))
for c in range(times):
example()
这是我正在尝试做的一个例子。
如果我在输入中键入“3”,我希望我的 .txt 文件包含我创建的函数的输出,即:
hello, world!
hello, world!
hello, world!
那可能吗?如果是这样,怎么做?
解决方案
当然可以!首先,您需要打开文件,重要的是您正在编写的程序位于其文件夹中。以下是如何做到这一点:(
open ('the_file_name.txt', 'a')
“a”作为附加)。当然,你还没有写。您可以通过将文件 argentum 添加到打印命令来执行此操作:print ('hello, world!', File = 'the_file_name.txt')
完整代码:
open ('the_file_name.txt', 'a')
def example ():
print ("hello, world!", file = 'the_file_name.txt')
times = int (input ("how many 'hello worlds'?"))
for c in range (times):
example ()