如果“文件名”不存在,我想使用 pd.write_csv 写入“文件名”(带标题),否则附加到“文件名”(如果存在)。如果我只是使用命令:
df.to_csv('filename.csv',mode = 'a',header ='column_names')
写入或追加成功,但似乎每次追加发生时都会写入标头。
如何仅在文件不存在时添加标头,并在文件存在时不添加标头?
不确定 pandas 有没有办法,但检查文件是否存在是一个简单的方法:
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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)