0

Trying to read in a CSV, adding a row at the bottom, and deleting a row at the top. I have not been able to find a way to delete a row in the dictwriter object without converting to a list, deleting the row in the list, then writing it out using csv.writer.

Should be a better way than reading/writing twice. python3.8, ubuntu Thx.

stime = get_time_str()

new_dict = {'Time': stime, 'Queries': Querycounter.value}
Querycounter.value = 0

# list of column names
field_names = ['Time', 'Queries']

# Open CSV file in append mode
#append the new queries count at the end of the file
with open(AlpacaQueriesCSVfile, 'a') as f_object:
    dictwriter_object = DictWriter(f_object, fieldnames=field_names)
    dictwriter_object.writerow(new_dict)
    f_object.close()
        
#open using csv.reader, delete the rows(s).
with open(AlpacaQueriesCSVfile, "r") as f:
    reader = csv.reader(f, delimiter=",")
    data = list(reader) #should be a better way of doing this by deleting rows in the dictwriter_object above....later

row_count = len(data)
if row_count > 2880:
    logger.debug('Deleting row from Queries.csv ')
    to_skip = row_count-2880
    del data[1:to_skip]  # leave first row
    with open(QueriesCSVfile, 'w') as f:
        write = csv.writer(f)
        write.writerows(data)
creeser
  • 363
  • 1
  • 4
  • 11
  • Idea within one context-manager aka `with` statement: open for both read/write (I think mode a+), read all lines, drop 1st, add last, write. – mechanical_meat Nov 13 '21 at 03:22
  • *Should be a better way than reading/writing twice.*... Hi, there! I think [this answer](https://stackoverflow.com/a/17646946/246801) to this SO question, 'writing back into the same file after reading from the file', addresses that sentiment that there should be a better way. You have two options: open A for reading and accumulate/process data, then open A for writing and "save" that data; or... write to B as you are reading from A, them move/rename B to A. – Zach Young Nov 13 '21 at 17:32
  • Does dictwriter allow you to delete a row? – creeser Nov 14 '21 at 01:17

0 Answers0