写入CSV

时间:2014-02-28 18:28:23

标签: python csv

由于某种原因,它没有写入CSV。谁能明白为什么不写?

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

这是打印输出:

['jim.weirich@gmail.com', 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?

2 个答案:

答案 0 :(得分:2)

您的代码肯定是在编写CSV,但我想您不知道目录的位置在哪里。

print os.getcwd()添加到您的调试输出中,然后查看那个位置。

或者更好的是,使用绝对路径打开CSV文件以确保将其写入已知位置。您可以使用脚本的文件名作为开头:

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

现在,您的CSV文件将始终在与脚本相同的目录中创建。

如果您的脚本永远不会退出,则在Windows关闭文件之前,您将看不到写入的数据;您需要在某处存储对final_csv的引用,以便您可以在该对象上调用close()(无法从csv.writer()对象中检索它。)

在大多数平台上,还有一个缓冲区;如果只写几行,在刷新缓冲区之前可能看不到数据(通常在关闭时发生这种情况),你仍然需要final_csv引用并调用final_csv.flush()来刷新缓冲区到磁盘。

答案 1 :(得分:0)

这已有多个答案,但总结一下;

您需要在文件对象上调用close,或使用with