[英]to_csv storing columns label on every insert of data to csv file
当我第一次在 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)
csv 文件中的数据:
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')
output 文件在 append 模式下打开,默认情况下to_csv()
将包含 header 行。 您可以简单地关闭 header:
df.to_csv("hello.csv", header=False, sep="|", index=False, na_rep="null", mode='a')
这将起作用,但您的 CSV 文件将没有 header 行。 如果您需要 header 那么您可以检查 output CSV 文件是否已经存在,如果存在则禁用标头。
一种方法是@Eason在答案中建议,但是,由于额外的加载时间,这对于大文件可能不实用(可能这就是您使用 append 模式的原因?)
如果文件已存在且不为空,则以下禁用 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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.