GPB*_*GPB 34 python csv pandas
如果"filename"不存在,我想使用pd.write_csv写"filename"(带标题),否则如果存在则附加到"filename".如果我只是使用命令:
df.to_csv('filename.csv',mode = 'a',header ='column_names')
Run Code Online (Sandbox Code Playgroud)
写入或追加成功,但似乎每次发生追加时都会写入标题.
如果文件不存在,我怎么才能添加标题,如果文件存在则不添加标题?
Pad*_*ham 55
不确定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)
Run Code Online (Sandbox Code Playgroud)
小智 25
with open(filename, 'a') as f:
df.to_csv(f, mode='a', header=f.tell()==0)
Run Code Online (Sandbox Code Playgroud)
它会在第一次写入文件时添加标题
小智 11
在 Pandas 数据框“to_csv”函数中,如果 csv 文件存在并附加到现有文件,则使用 header=False。
import os
hdr = False if os.path.isfile('filename.csv') else True
df.to_csv('filename.csv', mode='a', header=hdr)
Run Code Online (Sandbox Code Playgroud)
上面的解决方案很棒,但我有道德义务在此处包含 pathlib 解决方案:
from pathlib import Path
file_path = Path(filename)
if file_path.exists():
df.to_csv(file_path, header=False, mode='a')
else:
df.to_csv(file_path, header=True, mode='w')
Run Code Online (Sandbox Code Playgroud)
或者(取决于您的内联偏好):
file_exists = file_path.exists()
df.to_csv(file_path, header=not file_exists, mode='a' if file_exists else 'w')
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
38518 次 |
最近记录: |