Im trying to append values from stored values taken from users. Is there a way to hard code the headers ("Player Name", "Age" and "Number") so evertime I run the code these headers dont appear again in the csv.
Edit: I want the headers to appear the "First time" it runs and not the ones after
data = {'Player Name': [playersNames[0]],
'Age': [Age[0]],
'Number': [number],
df = pd.DataFrame(data)
df.to_csv("Info.csv",mode='a',index=False, header=True)
print(df)
At the moment it does this:
Player Name,Age,Number
x,15,73
Player Name,Age,Number
y,25,70
CodePudding user response:
If you don't want the header to be appended as well, then set headers=False
in your call to to_csv
.
In this situation, if you are running the script multiple times but only want headers appended on the first execution, then you could check if the file exists.
import os
exists = os.path.exists('Info.csv')
Then, set headers=not exists
when calling to_csv
.
Docs here.
CodePudding user response:
Try:
import pathlib
csvfile = pathlib.Path('Info.csv')
df.to_csv(csvfile, mode='a', index=False, header=not csvfile.exists())