Код:
# 1. Doesn't mutate the input list
# 2. Doesn't waste memory on a temporary list of rows
# 3. Handles the CSV requirement, including quoting strings properly
float_type = type(0.0)
def csv_escape(pyrow, quotechar='"', delimiter=',', terminator='\r\n'):
outlist = []
for obj in pyrow:
if isinstance(obj, float_type):
s = repr(obj) # Get full precision. BTW the csv module doesn't do this :-(
else:
s = str(obj) # This may need further elaboration
if quotechar in s:
x = quotechar + s.replace(quotechar, quotechar+quotechar) + quotechar
elif delimiter in s or '\r' in s or '\n' in s:
x = quotechar + s + quotechar
else:
x = s
outlist.append(x)
return delimiter.join(outlist) + terminator
def emit_list_in_slices(alist, file_handle,
slice_size=5, pad_value=0, slice_formatter=csv_escape):
for i in xrange(0, len(alist), slice_size):
row = alist[i:i+slice_size]
n = len(row)
if n and n != slice_size:
row.extend([pad_value] * (slice_size - n))
file_handle.write(csv_escape(row))
if __name__ == "__main__":
test_list = range(9) + [1.0/11.0, 'He said "Hello"', 'foo,bar', 'zot']
f = open('demo.csv', 'wb') #### Note: binary
emit_list_in_slices(test_list, f)
f.close()
Запуск с этим Python: Python 2.1.3 (# 35, 8 апреля 2002, 17:47:50) [MSC 32 бит (Intel)] на win32:
C:\junk>\python21\python csvslice21.py
C:\junk>more demo.csv
0,1,2,3,4
5,6,7,8,0.090909090909090912
"He said ""Hello""","foo,bar",zot,0,0
Мм, должен признать, что я забыл, что было возможно в те дни ... –
@user: Есть ли какой-либо причине вы все еще используете 2.1? Он был выпущен 17 апреля 2001 года. – user225312
Да, используя старую версию zope. Мы переходим к новой версии и новой структуре, но для старой версии все еще нужны обновления :( – user571565