dropWizard
dropWizard

Reputation: 3538

Writing to a CSV

For some reason it isn't writing to the CSV. Can anyone see why it wouldn't write?

def main():
    list_of_emails = read_email_csv() #read input file, create list of emails
    master_list_writer = open_master_list() #open output file so we can write to it
    .....
    write_to_csv(master_list_writer, list_of_url, linkedin_information, facebook_information, twitter_information)

def open_master_list():
    final_csv = open('ruby_dev_final1.csv', 'wb')
    output_writer = csv.writer(final_csv)
    return output_writer

def write_to_csv(master_list_writer, list_of_urls, linkedin_information, facebook_information, twitter_information): #add in linkedin_list
master_list_writer.writerow(list_of_urls + linkedin_information + facebook_information + twitter_information)
  print list_of_urls, linkedin_information, facebook_information, twitter_information
  print 'is this working?'
  return

This is the print out:

['[email protected]', u'Cincinnati Area', u'http://www.facebook.com/jimweirich', u'http://www.linkedin.com/in/jimweirich', u'http://twitter.com/jimweirich'] ['Jim', 'Weirich', 'Chief Scientist', 'Neo', 'Cincinnati Area', 'P1Y10M', 'Present'] ['', '', ''] ['', '', '', '']
is this working?

Upvotes: 1

Views: 226

Answers (2)

jmetz
jmetz

Reputation: 12773

There are multiple answers to this already, but to summarize;

You need to call close on the file object, or use with

See

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121196

Your code is definitely writing the CSV, but I guess you don't know where the directory is where it is written.

Add a print os.getcwd() to your debug output too, then look in that location.

Or better still, use an absolute path to open the CSV file to ensure it is written to a known location instead. You could use the filename of the script as a start:

import os.path

base = os.path.basename(os.path.abspath(__file__))

def open_master_list():
    final_csv = open(os.path.join(base, 'ruby_dev_final1.csv'), 'wb')
    output_writer = csv.writer(final_csv)
    return output_writer

Now your CSV file will always be created in the same directory as the script.

If your script never exits, on Windows you won't see the data written until you close the file; you'd need to store a reference to final_csv somewhere so you can call close() on that object (you cannot retrieve it from the csv.writer() object).

On most platforms, there is also a buffer; if you write only a few rows, you may not see data until the buffer has been flushed (normally this happens on close), you'll need the final_csv reference still and call final_csv.flush() to flush the buffer to disk.

Upvotes: 2

Related Questions