Python write 2 lists and Pandas DataFrames to csv/excel sequentially

。_饼干妹妹 提交于 2019-12-06 04:37:43

pd.to_csv() accepts a file handle as input, not just a file name. So you can open a file handle and write multiple files into it. Here's an example:

from __future__ import print_function

with open('output.csv', 'w') as handle:
    for line in list_1:
        print(line, handle)
    df1.to_csv(handle, index=False)
    for line in list_2:
        print(line, handle)
    df2.to_csv(handle, index=False)

The csv module provides your desired functionality:

import csv
with open('SO Example.csv', 'w') as f:
    writer = csv.writer(f, lineterminator='\n')
    writer.writerow(list_1)
    writer.writerow(df1.columns)
    writer.writerows(df1.values)
    writer.writerow(list_2)
    writer.writerow(df2.columns)
    writer.writerows(df2.values)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!