在同一行中将变量和列表写入 csv

Writing variables and list to csv in the same row

我一直在尝试将变量和列表写入 csv 文件,事情是这样的:

import csv

foo=bar
foo1=bar2
list=[element,element2,element3]

with open('file.csv', 'w',newline='') as f:
    writer = csv.writer(f)
    writer.writerow([foo,list,foo1])

如果我在打开 csv 时这样做,我有这个,我真的不想要:

bar,[element,element2,element3], bar2

我希望最终结果是:

bar,element,element2,element3, bar2

有可能吗?

您可以通过在调用 writerow:

时附加列表来完成此操作
import csv

foo=bar
foo1=bar2
list=[element,element2,element3]

with open('file.csv', 'w',newline='') as f:
   writer = csv.writer(f)
   writer.writerow([foo]+list+[foo1]) # Changed this line