将列表写入csv文件,而不是根据需要编写

时间:2018-03-02 12:58:51

标签: python python-3.x csv writer

当我运行此代码时,每个列表项被分成单独的字母并用逗号分隔。

例如,如果我的列表stockName持有'amazon'并且tickerName持有'amzn'作为其每个受尊重列表中的第一项,则运行以下代码将其存储为:

a,m,a,z,o,n
a,m,z,n

实际上我想把它放在一行:

amazon,amzn

代码:

with open('/Users/reubenmcqueen/Desktop/csvStoreFile.csv', 'w',) as myFile:
    writer = csv.writer(myFile)
    for a in range(0, len(stockName)):
        i = [stockName[a], tickerName[a]]
        writer.writerows(i)

2 个答案:

答案 0 :(得分:0)

您应该使用writer.writerow(...)

stockName = ['amazon', 'apple']
tickerName = ['amzn', 'aapl']

with open('test.csv', 'w',) as myFile:
    writer = csv.writer(myFile)
    for stock, ticker in zip(stockName, tickerName):
        writer.writerow([stock, ticker])

答案 1 :(得分:-1)

像这样使用writer.writerow(a,b)

data = ['amazon','amzn']
with open('art_ton_prices.csv','a') as test:
    writer = csv.writer(test)
    writer.writerow(data[0], data[1])