如何将函数输出转储到.txt文件?

2024-06-01 09:27:21 发布

您现在位置:Python中文网/ 问答频道 /正文

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!

可能吗?如果是,怎么做


Tags: inhelloforworldinputexampledefrange
3条回答
def example():
    print("hello, world!")

times = int(input("how many 'hello worlds'? "))

如果要在每个循环上写入一个新文件,请以“w”的形式打开该文件,以便

output = ''
for c in range(times):
    output = f'{output}{example()}\n'
with open('./MyFile.txt', 'w') as f:
    f.write(output)

另外,如果您想在不清除文件的情况下写入,请将其作为“a”打开,即append,因此

with open('./MyFile.txt', 'a') as f:

但请确保该文件已存在

你当然可以! 首先,您需要打开该文件,为此编写的程序必须位于该文件的文件夹中。以下是如何做到这一点: open ('the_file_name.txt', 'a')(“a”作为追加)。当然,你还没有写信。您可以通过将文件argentum添加到print命令来实现这一点: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 ()  

您可以重新编写一点代码,但现在应该将“hello,world”文本保存在新行上

def example():
return "hello, world!"


times = int(input("how many 'hello worlds'? "))
data = []
for c in range(times):
    data.append(example())

file = open('finename.txt', 'w')
with file as f:
  for line in data:
    f.write(f'{line}\n')

相关问题 更多 >