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.