将数据写入CSV文件

时间:2018-10-31 17:25:36

标签: python python-3.x csv

我有一个基本上可以做到这一点的代码:

row1 = []
count = 0
writer = csv.writer(myFile)
row = []
for j in range(0, 2):
    for i in range(0, 4):
        row1.append(i+count)
    count = count + 1
    print(row1)
    writer.writerows(row1)
    row1[:] = []

我正在创建一些列表,我想将每个值映射到一列,就像这样

enter image description here

此错误将其显示为iterable expected。我该怎么办?

3 个答案:

答案 0 :(得分:2)

@roganjosh是正确的,您一次只需要写一行是writerow

import csv

myFile = open("aaa.csv", "w", newline="")

row1 = []
count = 0
writer = csv.writer(myFile)
row = []
for j in range(0, 2):
    for i in range(0, 4):
        row1.append(i+count)
    count = count + 1
    print(row1)
    writer.writerow(row1)
    row1[:] = []

myFile.close() # Don't forget to close your file

答案 1 :(得分:1)

您可能需要调用方法.writerow()而不是复数.writerows(),因为在每次调用时都在文件中写入一行。

另一种方法是一次将多行写入文件。


或者您也可以像这样重组代码以在末尾写所有行:

import csv

row_list = []
for j in range(2):
    row = [j+i for i in range(4)]
    row_list.append(row)
# row_list = [
#     [j+i for i in range(4)]
#     for j in range(2)]

with open('filename.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerows(row_list)

答案 2 :(得分:0)

pandas中操作表格数据要简单得多-是否有不想使用熊猫的原因?

import pandas as pd

df = pd.DataFrame()

for i in range(4):
    df[i] = range(i, i+4)

# Any other data wrangling

df.to_csv("file.csv")