I tried many ways/combinations to insert headers (I need to add two column headers) but the file doesn't accept headers at file creation. At best, I get headers as rows come into the file one after the other. I can't see how to enter the headers only once persistently. Can you see in the code below where I could make some change please? Thanks.
with open(MYFILE, "w", newline='') as csvWriter, open('read.csv', 'r', newline='') as csvReader:
if keyword != "q":
fieldnames = [engine, keyword]
#fieldnames = ['Engine', 'Keywords']
# writer = csv.DictWriter(csvWriter, fieldnames=[engine, keyword], extrasaction='ignore')
writer = csv.DictWriter(csvWriter, fieldnames=fieldnames)
writer.writeheader()
reader = csv.DictReader(csvReader, fieldnames=fieldnames)
writer.writerow({"Engine": engine, "Keywords": keyword})
writer.writerows(reader)
I'm trying to save data into a csv file. I have two columns but no headers currently. I'd need some column titles like in any spreadsheet basically.
UPDATE ============================================== I've tried to insert to no avail the first block hereafter before and after the 2nd one. There is certainly something I'm not doing right but I don't know. Any suggestion, please?
STATUS = "quit"
print("Press [q] to quit at any time")
menu_engine = {}
menu_engine['1'] = "Google Search - Large Results"
menu_engine['2'] = "Google Search - Small Results"
menu_engine['3'] = "Yahoo Search - Large Results"
menu_engine['4'] = "Yahoo Search - Small Results"
while True:
options = menu_engine.keys()
for entry in options:
print(entry, menu_engine[entry])
engine = input("Enter your Type of Search: ")
while STATUS != "q":
keyword = input("Enter keyword(s): ")
with open(MYFILE, "a", newline='') as csvWriter:
if keyword != "q":
fieldnames = [engine, keyword]
writer = csv.DictWriter(csvWriter, fieldnames=fieldnames, extrasaction='ignore')
writer.writeheader()
THE EXPECTED OUTPUT in the CSV File:
Engine Number,Keywords
4,man man
4,mate mate