csv:writer.writerows()拆分我的字符串输入

时间:2015-12-15 09:16:13

标签: python csv

我有一个字符串列表,我想写一个csv文件。列表list_results看起来像

['False, 60, 40 ', 'True, 70, 30, ']

所以,我会尝试这样的事情:

with open('example1.csv', 'w') as result:
    writer = csv.writer(result, delimiter=",")
    writer.writerow( ('Correct?', 'Successes', 'Failures') )
    writer.writerows(list_results)

不幸的是,数据并没有写入三列。我找到了:

['Correct?', 'Successes', 'Failures']  
['F', 'a', 'l', 's', 'e', ',', ' ', '6', '0', ',', ' ', '4', '0', ' ']  
['T', 'r', 'u', 'e', ',', ' ', '7', '0', ',', ' ', '3', '0', ',', ' ']

如何正确格式化此行为以获取

['Correct?', 'Successes', 'Failures']  
['False', 60, 40]  
['True', 70, 30]

最好采用格式%s %d %d

4 个答案:

答案 0 :(得分:2)

您最后使用writer.writerows() s。该方法需要一个列表列表,但是您传入了一个字符串列表。 writerows()方法实际上是这样做的:

def writerows(self, rows):
    for row in rows:
        self.writerow(row)

其中每行必须是一系列列。字符串是一系列单个字符,因此您所写的内容是:由您选择的分隔符分隔的单个字符。

您需要将字符串拆分为列,不要自己包含逗号,编写者对象的工作包括:

with open('example1.csv', 'w') as result:
    writer = csv.writer(result, delimiter=",")
    writer.writerow(('Correct?', 'Successes', 'Failures'))
    for row in list_results:
        columns = [c.strip() for c in row.strip(', ').split(',')]
        writer.writerow(columns)

或使用生成器表达式,以便继续使用writerows()

with open('example1.csv', 'w') as result:
    writer = csv.writer(result, delimiter=",")
    writer.writerow(('Correct?', 'Successes', 'Failures'))
    writer.writerows([c.strip() for c in r.strip(', ').split(',')]
                     for r in list_results)

演示:

>>> import csv
>>> list_results = ['False, 60, 40 ', 'True, 70, 30, ']
>>> import csv
>>> import sys
>>> list_results = ['False, 60, 40 ', 'True, 70, 30, ']
>>> writer = csv.writer(sys.stdout)
>>> writer.writerow(('Correct?', 'Successes', 'Failures'))
Correct?,Successes,Failures
>>> for row in list_results:
...     columns = [c.strip() for c in row.strip(', ').split(',')]
...     writer.writerow(columns)
...
False,60,40
True,70,30
>>> writer.writerows([c.strip() for c in r.strip(', ').split(',')]
...                  for r in list_results)
False,60,40
True,70,30

答案 1 :(得分:0)

您的list_results很可能包含以下内容:

['False, 60, 40 ', 'True, 70, 30, ']

writerows()获取列表列表,提供字符串列表,字符串可迭代,因此转换为字符列表,您想要的是:

with open('example1.csv', 'w') as result:
    writer = csv.writer(result, delimiter=",")
    writer.writerow( ('Correct?', 'Successes', 'Failures') )
    writer.writerows([c.strip() for c in r.split(',')] for r in list_results)

答案 2 :(得分:0)

它工作正常:

list_results = [(False, 60, 40), (True, 70, 30)]

这是C上writer.writerows()的源代码。


static PyObject *
csv_writerows(WriterObj *self, PyObject *seqseq)
{
    PyObject *row_iter, *row_obj, *result;

row_iter = PyObject_GetIter(seqseq);
if (row_iter == NULL) {
    PyErr_SetString(PyExc_TypeError,
                    "writerows() argument must be iterable");
    return NULL;
}
while ((row_obj = PyIter_Next(row_iter))) {
    result = csv_writerow(self, row_obj);
    Py_DECREF(row_obj);
    if (!result) {
        Py_DECREF(row_iter);
        return NULL;
    }
    else
         Py_DECREF(result);
}
Py_DECREF(row_iter);
if (PyErr_Occurred())
    return NULL;
Py_INCREF(Py_None);
return Py_None;

}

答案 3 :(得分:-1)

writerows需要列表清单。因此,如果您将列表提供给writerows,它会将其转换为列表列表(即将单词分成字母。

import csv
list_results = ['False, 60, 40 ', 'True, 70, 30, ']

with open(r"C:\test.csv", 'wb') as result:
    writer = csv.writer(result, delimiter=",")
    writer.writerow( ('Correct?', 'Successes', 'Failures') )
    writer.writerows([i.strip().split(',') for i in list_results])

或者如果您想使用writerow -

import csv
list_results = ['False, 60, 40 ', 'True, 70, 30, ']

with open(r"C:\mnp_.csv", 'wb') as result:
    writer = csv.writer(result, delimiter=",")
    writer.writerow( ('Correct?', 'Successes', 'Failures') )
    data = [i.strip().split(',') for i in list_results]
    for d in data:
        writer.writerow(d)

输出 -

Correct?    Successes   Failures
FALSE   60  40
TRUE    70  30