Panda 的 Write CSV - Append vs. Write [英] Panda's Write CSV - Append vs. Write

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

问题描述

如果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)

这篇关于Panda 的 Write CSV - Append vs. Write的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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