I've written some code that is supposed to be aware of if a CSV file exists and append to it if it's the right format, or erase it and create a new file.
The part where it checks if the format is correct (by checking the CSV headers to see if they are equal) is not working, because for some weird reason the readline() function is ignoring the headers (which should be the first line of the CSV file.
Do note that I don't want to use extra dependencies such as Pandas.
import os, csv
path = 'intent_outputs.csv'
response = {'query':'eggs', 'header':'eggs', 'fulfillmentText':'are tasty', 'buttontext':'VISIT PAGE', 'buttonurl':'eggs.com', 'contextbuttontext':'eggs', 'contextbuttonurl':'eggs.com'}
output = open(path, 'a')
csv_columns = ['Query', 'Header', 'Text', 'Button Text', 'Button URL', 'Context Button Text', 'Context Button URL']
writer = csv.DictWriter(output, fieldnames=csv_columns)
if not os.path.exists(path):
print("DOES NOT EXIST")
output = open(path, 'w')
else:
print("EXISTS")
output = open(path, 'r')
if(output.readline() != ",".join(csv_columns)):
print("NOT EQUAL")
try:
output = open(path, 'w')
writer.writeheader()
except IOError:
print("IOError")
else:
print("EQUAL")
output = open(path, 'a')
try:
row = {'Query':response['query'], 'Header':response['header'], 'Text':response['fulfillmentText'], 'Button Text':response['buttontext'], 'Button URL':response['buttonurl'], 'Context Button Text':response['contextbuttontext'], 'Context Button URL':response['contextbuttonurl']}
writer.writerow(row)
except IOError:
print("I/O error")
Here's Johnny intent_outputs.csv:
Query,Header,Text,Button Text,Button URL,Context Button Text,Context Button URL
eggs,eggs,are tasty,VISIT PAGE,eggs.com,eggs,eggs.com
I want to read the first line (starting with "Query....") but it's being actively ignored.
output = open(path, 'a')and lateroutput = open(path, 'w')without closing the file in between; this seems like a breathing ground for unintended behavior. Are you sure that this is a good way to go?open()to initializecsv.DictWriter()(the'a'flag is to prevent overwriting and permit appending to the file if all of the if-else checks pass), and in the latter the'w'tag is so that I can erase the file and overwrite new headers. I am not sure it is a great idea, though......with open(my_file, flag) as foocontext manager.