Reputation: 39
I could use some help here. I am attempting to append a DateTime Index that I have converted to a list to an existing CSV file. When I run the code the list does append as intended but the times are comma separated whereas the list being used to append the data is not. My code is below
import csv
import numpy as np
import datetime
import pandas as pd
time_now = datetime.datetime.now() + datetime.timedelta(minutes = 5)
time_future = time_now + datetime.timedelta(minutes = 30)
time_predict = pd.date_range(time_now, time_future, freq = '5min')
time_predict_list = time_predict.strftime("%Y-%m-%d %H:%M:%S").tolist()
overwrite = input("Would You like to Overwrite or Append Prediction Data? Type (a) to Append, Type (o) to Overwrite: ")
if overwrite == "o":
np.savetxt("time_list.csv",
time_predict_list,
delimiter =", ",
fmt ='% s')
def append_list_as_row(file_name, list_of_elem):
with open(file_name, 'a+', newline='') as file:
csv_writer = csv.writer(file)
csv_writer.writerows(list_of_elem)
if overwrite != "o":
append_list_as_row('time_list.csv',time_predict_list)
Actual output:
2021-02-08 10:54:31
2021-02-08 10:59:31
2021-02-08 11:04:31
2021-02-08 11:09:31
2021-02-08 11:14:31
2021-02-08 11:19:31
2021-02-08 11:24:31
2,0,2,1,-,0,2,-,0,8, ,1,0,:,5,4,:,5,1
2,0,2,1,-,0,2,-,0,8, ,1,0,:,5,9,:,5,1
2,0,2,1,-,0,2,-,0,8, ,1,1,:,0,4,:,5,1
2,0,2,1,-,0,2,-,0,8, ,1,1,:,0,9,:,5,1
2,0,2,1,-,0,2,-,0,8, ,1,1,:,1,4,:,5,1
2,0,2,1,-,0,2,-,0,8, ,1,1,:,1,9,:,5,1
2,0,2,1,-,0,2,-,0,8, ,1,1,:,2,4,:,5,1
Then intended output would be the same values in rows 8-14 but without being separated by commas
Upvotes: 0
Views: 281
Reputation: 177891
writerows
is incorrect. It requires a list of lists. A list of strings looks like a list of lists because strings are iterables of characters.
Use writerow
, but to put each item on a separate line each "row" needs to be a list of the items in the row. In this case, that is a single item:
for row in list_of_elem:
csv_writer.writerow([row])
You don't really need the csv
module when you can open the file in the mode you want. Pass an opened file to np.savetext
:
import datetime
import numpy as np
import pandas as pd
def append_list_as_row(file_name, list_of_elem):
with open(file_name, 'a') as file:
for row in list_of_elem:
print(row,file=file)
time_now = datetime.datetime.now() + datetime.timedelta(minutes = 5)
time_future = time_now + datetime.timedelta(minutes = 30)
time_predict = pd.date_range(time_now, time_future, freq = '5min')
time_predict_list = time_predict.strftime("%Y-%m-%d %H:%M:%S").tolist()
overwrite = input("Would You like to Overwrite or Append Prediction Data? Type (a) to Append, Type (o) to Overwrite: ")
with open('time_list.csv', 'w' if overwrite == 'o' else 'a') as file:
np.savetxt(file, time_predict_list, fmt='%s')
Upvotes: 1