麻烦写一个csv

时间:2012-11-04 04:08:56

标签: python csv

我试图编写一个脚本,以便输出为5列的.csv:2个数据,后跟空列,然后是2个数据列。以下是what I get,此处为what I'd like。为了完整起见,这是我的所有代码。

import requests
import csv

item_dictionary = {'10350': 'Third-Age Full', '560':'Death Rune'}
item_ids = item_dictionary.keys()
url_template = 'http://www.grandexchangecentral.com/include/gecgraphjson.php?jsid=%r'

sites = []
for i in range(0, len(item_ids)):
    result = url_template % item_ids[i]
    sites.append(result)


def data_grabber(item): 
    url = item
    r = requests.get(url, headers={'Referer': 'www.grandexchangecentral.com'})
    data = r.json  
    prices = [i[1] for i in data]
    return prices


data = map(data_grabber, sites)

names = item_dictionary.values()

def writer(item):
    q = data.index(item) 
    headers = [names[q], 'Percent Change', None]   
    a = data[q]
    percents = [100.0 * a1 / a2 - 100 for a1, a2 in zip(a[1:], a)]
    percents.insert(0, None)
    f = zip(data[q], percents)
    myfile = open('prices.csv', 'wb')
    wr = csv.writer(myfile)
    wr.writerow(headers)
    wr.writerows(f)
    myfile.close()

z = [writer(x) for x in data]

我认为发生的事情是writer(item)写两列,而z的下一次迭代会覆盖这些列。编辑:我注意到我在函数中有myfile.close()。这可以解释它,但我不知道如何解决它。

2 个答案:

答案 0 :(得分:0)

如果,并且只有在编写非常简单的CSV之类的情况下,那么您并不需要csv包。只需打开文件并写下:

f = open("out.csv", "w")
...
for line in lines:
    //line = ["col1","col2","","col3",""]
    csv_line = str.join(",",line)
    f.writeline(csv_line)
f.close()

如果您的数据更复杂(即不是纯数字),则会遇到问题。

答案 1 :(得分:0)

只打开一次文件,然后:

wr = csv.writer(myfile)
wr.writerow(headers)
for x in data:
    # prepare row data
    # ... (the modified body of writer() function goes here)
    # write it as csv
    wr.writerow(row) # row is a list with 5 items
myfile.close()

在“wb”模式下打开文件时,其大小将被截断为零,之前的内容将丢失。因此,当您多次调用writer()函数时,它会替换所有以前的内容,只有最后一次调用的行才会保留在文件中。