简体   繁体   English

使用文件写入操作将5M数据写入CSV文件

[英]write 5M data to a csv file using file write operation

I'm writing some data in a single column of a CSV file using file write operation. 我正在使用文件写入操作在CSV文件的单个列中写入一些数据。 I am able to write values only in 1048576 rows. 我只能在1048576行中写入值。 I have 5 million integer data values and I want it to be saved in a single CSV file. 我有500万个整数数据值,并且希望将其保存在单个CSV文件中。 Below is my code 下面是我的代码

with open(path, 'w') as fp:
    for i in range(0,len(values)):
        fp.write(values[i] + '\n')
    fp.close()
  • Is it possible to continue writing values after 1048576 rows to 3rd/4th column of the CSV file?? 是否可以继续将1048576行之后的值写入CSV文件的第3/4列? OR 要么

  • Is it possible to write values in a sequential way so that i can have all the values in a single file? 是否可以按顺序写入值,以便我可以将所有值保存在一个文件中?

You can use itertools.izip_longest to "chunk" the values into "columns", then use the csv module to write those rows to the file. 您可以使用itertools.izip_longest将值“分类”为“列”,然后使用csv模块将这些行写入文件。 eg: 例如:

import csv
from itertools import izip_longest

N = 5 # adapt as needed
values = range(1, 23) # use real values here

with open(path, 'wb') as fout:
    csvout = csv.writer(fout)
    rows = izip_longest(*[iter(values)] * N, fillvalue='')
    csvout.writerows(rows)

This will give you the following output: 这将为您提供以下输出:

1,2,3,4,5
6,7,8,9,10
11,12,13,14,15
16,17,18,19,20
21,22,,,

You can also "transpose" the data so the data "runs the other way round", eg: 您还可以“转置”数据,以使数据“反过来运行”,例如:

import csv
from itertools import izip_longest, izip

N = 5 # adapt as needed
values = range(1, 23) # use real values here

with open(path, 'wb') as fout:
    csvout = csv.writer(fout)
    rows = izip_longest(*[iter(values)] * N, fillvalue='')
    transposed = izip(*rows)
    csvout.writerows(transposed)

This will give you: 这将为您提供:

1,6,11,16,21
2,7,12,17,22
3,8,13,18,
4,9,14,19,
5,10,15,20,

As an alternative, you can use islice to give you the required number of columns per row as follows: 或者,可以使用islice为您提供所需的每行列数,如下所示:

from itertools import islice
import csv

path = 'output.txt'
values = range(105)     # Create sample 'values' data
columns = 10
ivalues = iter(values)

with open(path, 'wb') as fp:
    csv_output = csv.writer(fp)
    for row in iter(lambda: list(islice(ivalues, columns)), []):
        csv_output.writerow(row)

Giving you the following: 给您以下内容:

0,1,2,3,4,5,6,7,8,9
10,11,12,13,14,15,16,17,18,19
20,21,22,23,24,25,26,27,28,29
30,31,32,33,34,35,36,37,38,39
40,41,42,43,44,45,46,47,48,49
50,51,52,53,54,55,56,57,58,59
60,61,62,63,64,65,66,67,68,69
70,71,72,73,74,75,76,77,78,79
80,81,82,83,84,85,86,87,88,89
90,91,92,93,94,95,96,97,98,99
100,101,102,103,104

Note, in your example, you should convert range to xrange to avoid Python creating a huge list of numbers to iterate on. 请注意,在您的示例中,应将range转换为xrange以避免Python创建大量的要迭代的数字列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM