繁体   English   中英

如何保存打印语句的输出

[英]how to save the output of a print statement

我只想将每个 for 循环的打印语句的输出保存到一个名为 test.txt 的文本文件中,并且在文本文件中,每个 for 循环输出应该用 >>> 符号分隔,另外我想在文本文件的顶部为“column-a”。我试过的代码如下:

a = ['oof', 'rab', 'zab']
for i in range(1,5):
    for file in a:
        print('>>>')
        data=print(file)
with open(“test.txt”,w) as f: 
f.write(data)

通过执行上面的代码,我得到了如下所示

oof
rab
zab
oof
rab
zab
oof
rab
zab
oof
rab
zab

但我需要像下面这样的输出 test.txt

column-a
>>> 
oof
rab
zab
>>>
oof
rab
zab
>>>
oof
rab
zab
>>>
oof
rab
zab

我希望我能得到一些解决方案。提前致谢。

print语句可用于直接写入带有file关键字参数的打开文件:

items = ['oof', 'rab', 'zab']

with open('file.txt', 'w') as file:

    # header
    print('column-a', file=file)

    # loop with >>> separators
    for i in range(5):
        print('>>>', file=file)

        # print list items
        for item in items:
            print(item, file=file)

上面的代码创建了一个包含以下内容的file.txt文件:

column-a
>>>
oof
rab
zab
>>>
oof
rab
zab
>>>
oof
rab
zab
>>>
oof
rab
zab
>>>
oof
rab
zab

您只需要写入文件并打印到屏幕上。 请注意,您的代码中还有 UTF-8 "66 & 99" 双引号,而不是简单的"字符。

a = ['oof', 'rab', 'zab']
f = open( "test.txt", "wt" )
for i in range( 1, 5 ):
    for word in a:
        print( word )
        f.write( word + "\n" )
    print( '>>>' )
    f.write( '>>>' + "\n" )
f.close()

            

暂无
暂无

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

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