to_csv在每次插入数据到CSV文件时存储列标签



当我第一次在CSV文件中插入数据时,它是好的但第二次它还是插入了列名

import pandas as pd


name = input("Enter student name")
print("")
print("enter marks info below")
print("")
eng= input("enter English mark : ")
maths= input("enter Maths mark : ")
physics= input("enter Physics mark : ")
chemistry= input("enter Chemistry mark : ")
ip= input("enter Informatic Practices mark : ")
dict = {
"name":{name:name},
"english":{name:eng},
"maths":{name:maths},
"physics":{name:physics},
"chemistry":{name:chemistry},
"ip":{name:ip}
}
df= pd.DataFrame(dict)

df.to_csv("hello.csv", sep="|",index=False,na_rep="null",mode='a')
print("hello.csv")
read = pd.read_csv("hello.csv", sep='|')
print(read)

data in csv file:

name|english|maths|physics|chemistry|ip
dddd|dd|e3|3|3|3
name|english|maths|physics|chemistry|ip 
ddddddd|e33|33|3||3
name|english|maths|physics|chemistry|ip
dddddd|33|333||3|

请帮助解决如何修复,使列不被添加多次

您可以在每次运行此脚本之前读取CSV文件。

import pandas as pd
import os
df = pd.DataFrame() if not os.path.exists("hello.csv") else pd.read_csv("hello.csv", sep='|')
name = input("Enter student name")
print("")
print("enter marks info below")
print("")
eng = input("enter English mark : ")
maths = input("enter Maths mark : ")
physics = input("enter Physics mark : ")
chemistry = input("enter Chemistry mark : ")
ip = input("enter Informatic Practices mark : ")
dict = {
"name": {name: name},
"english": {name: eng},
"maths": {name: maths},
"physics": {name: physics},
"chemistry": {name: chemistry},
"ip": {name: ip}
}
df = df.append(pd.DataFrame(dict))
df.to_csv("hello.csv", sep="|", index=False, na_rep="null", mode='w')
print("hello.csv")
read = pd.read_csv("hello.csv", sep='|')
print(read)

,您也可以使用下面的代码导出没有列的df,但可能仍然需要先检查文件是否存在或列顺序。

df.to_csv('filename.csv', header=False, sep='|', mode='a')

以追加模式打开输出文件,to_csv()默认包含标题行。你可以简单地关闭标题:

df.to_csv("hello.csv", header=False, sep="|", index=False, na_rep="null", mode='a')

将工作,但您的CSV文件将没有标题行。如果您需要头文件,那么您可以检查输出CSV文件是否已经存在,如果存在则禁用头文件。

一种方法是@Eason回答中建议的,但是,由于额外的加载时间,对于大文件可能不实用(可能这就是您使用追加模式的原因?)

如果文件已存在且不为空,则以下命令禁用CSV头。

from pathlib import Path
header = True
p = Path('hello.csv')
if p.exists() and p.stat().st_size:
header = False
df.to_csv(p, header=header, sep="|", index=False, na_rep="null", mode='a')

最新更新