如何将列表转换为每行N个项目的CSV文件? [英] How to transform a list into a CSV file with N items per row?

查看:47
本文介绍了如何将列表转换为每行N个项目的CSV文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个新的CSV文件,每行3个项目. 我的源文件看起来像(没有新行/换行符):

I want to create a new CSV file with 3 items per row. My source file looks like (there are no new lines / line breaks):

12123, 1324, 232324, 243443, 234, 2345, 2334, 2445, 22355, 222234, 2345

现在,我想将此文件转换为CSV文件.取前三个元素,并将其放在第一行,新行中,并取下三个元素,依此类推...

Now I want to transform this file in a CSV file. Take the first three elements and put it in the first row, new line, and take the next three items, etc...

12123, 1324, 232324
24343, 234, 2345
...

如何使用Python 3.x做到这一点?我是Python新手,一无所获... 我以前的尝试:

How can I do that with Python 3.x? I'm new in Python and don't get it... My previous attempt:

import csv

with open('test.csv') as f:
    reader = csv.reader(f)
    with open('test2.csv', 'w') as csvfile:
        writer = csv.writer(csvfile)
        liste = list(reader)
        print(liste[1:2])

但是我的列表对象只有一个长项.

But my list object has only one long item.

推荐答案

您提到:

我的源文件看起来像(没有新行/换行符):

My source file looks like (there are no new lines / line breaks):

12123、1324、232324、243443、234、2345 2334、2445、22355、222234、2345

12123, 1324, 232324, 243443, 234, 2345 2334, 2445, 22355, 222234, 2345

因此,它将读取CSV的一长行,然后将其写为每行三列的组:

So this reads one long row of a CSV, then writes it as groups of three per line:

import csv

with open('test.csv',newline='') as f:
    reader = csv.reader(f)
    line = next(reader) # Read the one long line

with open('test2.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    for i in range(0,len(line),3): # step by threes.
        writer.writerow(line[i:i+3])

请注意,正确使用csv模块需要在Python 3中使用newline=''打开文件(在Python 2中为'rb'或'wb').

Note that correct use of the csv module requires the files to be opened with newline='' in Python 3 ('rb' or 'wb' in Python 2).

这篇关于如何将列表转换为每行N个项目的CSV文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆