I am trying to append values in csv(already exist) with python programming, if the column already exists, it should be replaced or if the data is new I need to append it in the same file
What I tried so far:
csv data:
SnapshotId,promotion level
1.9.0.0,Tested
2.0.0.1,Unit tested
Initial just appending (it works):
with codecs.open('sample.csv','a',encoding='utf8') as newFile:
newFileWriter = csv.writer(newFile)
newFileWriter.writerow([str(snapshot_id),str(unitTest)])
So later my requirement changes like if incoming data like snapshotid already exist I should update the respective row value with promotion level, if snapshot id is unique and doesn't exist, I should then append a new row with snapshot id and promotion level.
I just tried like this with pandas
import pandas as pd
import os,sys
snapID = sys.argv[1]
promLevel = sys.argv[2]
df = pd.read_csv('sample.csv')
def update_table(snapID, promLevel):
if snapID in df['SnapshotId']:
print("Updating promotion level")
df.loc[df['SnapshotId'] == snapID, ['promotion_level']] = promLevel
else:
print("Adding new snapshot")
return df.append({'SnapshotId': snapID, 'promotion_level': promLevel}, ignore_index=True)
return df
dd = update_table(str(snapID),promLevel)
print(dd)
I can able to locate the index but am not sure how to check if column already exists and replace the whole row with new values in csv any insights would be great help
to_csv. But Many of the database provides functionality what you requires :-)