如何将列表转换为每行n个项目的csv文件?

时间:2016-12-26 22:53:54

标签: python list python-3.x csv

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

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

现在我想在csv文件中转换此文件。取前三个元素并将其放在第一行,新行,并接下来的三个项目......

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

我如何使用Python 3.x做到这一点?我是Python的新手,并没有得到它...... 我以前的尝试:

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])

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

7 个答案:

答案 0 :(得分:1)

你提到了:

  

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

     

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

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

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')。

答案 1 :(得分:0)

文件I / O中立解决方案:

csv = """12123, 1324, 232324, 243443, 234, 2345

2334, 2445, 22355, 222234, 2345"""  # replace this with the file you read from CSV

def sixPerLineToThreePerLine(s):
  result = ""
  for line in s.split("\n"):
    sp = line.split(", ")
    result = result + ", ".join(sp[:3]) + "\n" + ", ".join(sp[3:])
  return result

print(sixPerLineToThreePerLine(csv))  # replace this with code to write to CSV

答案 2 :(得分:0)

这应该有所帮助。这是使用python 2.7编写的,所以如果你在3.x中运行它有任何问题,请告诉我,我可以尝试帮助。

import csv # import the csv module you will need, if you want to avoid this you can just read it in as a text file
output = """""" # make an output string
num = 0 #initialize num that trakcs how many numbers have ben read
with open('datacsv.csv', 'rb') as f: # open the input file
    file = csv.reader(f) # initialize the file as being a csv file
    for row in file: # for every row (you said no new lines, but just in case)
        for data in row: # for ever entry in the row
            if(num == 2): # if you have read in three numbers
                num = 0 # reset num
                output += data + "\n" # output a new line and the current number
            else:
                num += 1 # increment num
                output += data + "," # add to output the data and a comma


new = open("outputcsv.csv", "w") # create the output file
new.write(output) # write the output data to the new file

答案 3 :(得分:0)

这是一个解决方案,但它有点长。基本上我会将csv中的所有值写入列表,然后从列表中删除三个值并写入csv,直到没有值为止。

import csv

# just an example csv
with open('example.csv', 'w') as csvfile:
    # create example csv with a single row of numbers 0-19
    spamwriter = csv.writer(csvfile)
    spamwriter.writerow([i for i in range(20)])

# open file for reading, append values to list
l = []
with open('example.csv') as csvfile:
    # read the example file into a list
    reader = csv.reader(csvfile)
    for row in reader:
        for val in row:
            l.append(val)


# write to the original file with 3 values per line
with open('example.csv', 'w') as csvfile:
    spamwriter = csv.writer(csvfile)
    while l:
        try:
            # write to file 3 values at a time
            spamwriter.writerow(l[:3])
            l = l[3:]
        except:
            # add last bit of file, if file doesn't devide evenly by 3
            spamwriter.writerow(l)
            break

我建议您查看Pandas 我觉得用它操纵csvs要容易得多,但它不在标准库中。

答案 4 :(得分:0)

您要做的是从文件中读取数据,然后将其拆分为单个元素。一旦将其放入单个元素中,就可以将它们组成三个一组并写入输出文件。

这样的事情应该有效:

apple-touch-icon.png

答案 5 :(得分:0)

我写了一个简短的程序,我认为你做了你想做的事情:

它读取读取器文件中的所有行,然后只需将它们插入3:3的写入器文件中。)

import csv

def main():

    with open('ex.csv', 'rb') as f:
    reader = csv.reader(f)
    with open('ex2.csv', 'wb') as csvfile:
        writer = csv.writer(csvfile)
        pass_on = []

        for row in reader:
            #print row

            for c in xrange(0, len(row)): # passing on objects after count of 3
                if row[c]:
                    pass_on.append(row[c])


        print pass_on

        while pass_on:

            writer.writerow(pass_on[:3])
            pass_on = pass_on[3:]



    print "done"

if __name__ == '__main__':
    main()

答案 6 :(得分:0)

没有csv模块的四行解决方案:

with open('oneline_numbers.csv') as fobj_in, open('three_numbers.csv', 'w') as fobj_out:
    numbers = iter(entry.strip() for entry in next((fobj_in)).split(','))
    for line in zip(*[numbers] * 3):
        fobj_out.write(', '.join(line) + '\n')