有没有办法将循环输出写入文件?

时间:2021-06-17 15:49:58

标签: python-3.x for-loop

我写了这段代码:

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']

我该如何解决这个问题?

提前致谢。

1 个答案:

答案 0 :(得分:0)

替换

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

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

##use 打开文件时追加。