pandas 的写CSV - 附加和写 [英] Panda's Write CSV - Append vs. Write

查看:109
本文介绍了 pandas 的写CSV - 附加和写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果filename不存在,我想使用pd.write_csv来写filename(带标题),否则如果存在,则附加到filename。如果我只是使用命令:

I would like to use pd.write_csv to write "filename" (with headers) if "filename" doesn't exist, otherwise to append to "filename" if it exists. If I simply use command:

     df.to_csv('filename.csv',mode = 'a',header ='column_names')

写入或追加成功,但似乎每次追加地点。

The write or append succeeds, but it seems like the header is written every time an append takes place.

如果文件不存在,如何只添加标题,如果文件不存在,则如何附加无标题?

How can I only add the header if the file doesn't exist, and append without header if the file does exist?

推荐答案

不确定在pandas中有一种方法,但检查文件是否存在将是一个简单的方法:

Not sure there is a way in pandas but checking if the file exists would be a simple approach:

import os
# if file does not exist write header 
if not os.path.isfile('filename.csv'):
   df.to_csv('filename.csv',header ='column_names')
else: # else it exists so append without writing the header
    df.to_csv('filename.csv',mode = 'a',header=False)

这篇关于 pandas 的写CSV - 附加和写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆