【问题标题】:Is there a way to write loop output to a file?有没有办法将循环输出写入文件?
【发布时间】:2021-06-17 15:49:58
【问题描述】:

我已经写了这段代码:

for i in range(0, 3):
    for g in range(1, 4):
        if i+1==g:
            a = f'''r{g} = {list(df.iloc[i])}'''
            with open('output.txt', 'w') as f:
                f.write(f'''{a}''')

这是我期待的输出:

r1 = ['kane', 'grealish', 'sancho', 'sterling']
r2 = ['foden', 'mount', 'bellingham', 'reece']
r3 = ['trippier', 'stones', 'walker', 'coady']

但是,我只是得到 r3 = ['trippier', 'stones', 'walker', 'coady']

我该如何解决这个问题?

提前致谢。

【问题讨论】:

  • w 模式打开文件会擦除现有内容。因此,您每次都在通过循环擦除文件。
  • 在打开文件时使用a 而不是w 以便追加
  • 提醒一下,像这样在一个紧密的循环中反复打开和关闭文件是相当低效的。

标签: python-3.x for-loop


【解决方案1】:

替换

with open('output.txt', 'w') as f:

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

##打开文件时使用追加。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-29
    • 1970-01-01
    • 2020-05-29
    相关资源
    最近更新 更多