如何复制CSV行row_number次?

时间:2016-06-20 19:57:19

标签: python loops csv

我正在尝试使用Python生成CSV文件“distance”,我想复制另一个文件的行,“结果”如下:

result.csv:

|ID |
|---|
| 1 |
| 2 |
| 3 |
...

distances.csv

|ID1 |ID2 |
|----|----|
| 1  | 1  |
| 1  | 2  |
| 1  | 3  |
| 2  | 1  |
| 2  | 2  |
| 2  | 3  |
...

这是我的Python代码:

with open('distances.csv', 'wb') as ff:
    writer = csv.writer(ff, delimiter=";", quoting=csv.QUOTE_ALL)

    with open('result.csv', 'rb') as f:
        reader = csv.reader(f, delimiter=";", quoting=csv.QUOTE_NONE)
        reader2 = csv.reader(f, delimiter=";", quoting=csv.QUOTE_NONE)

        for row in reader:
            for row2 in reader2:
                lst = []
                lst.append(row[0])
                lst.append(row[1])
                lst.append(row2[0])
                lst.append(row2[1])

                writer.writerow([unicode(s).encode("utf-8") for s in lst])

由于某种原因,它只复制了result.csv

中的第一行

提前致谢!

2 个答案:

答案 0 :(得分:2)

您可以使用itertools.productID中的distance.csv栏上重复:

from itertools import product
import csv


with open('result.csv', 'r') as fin, open('distance.csv', 'w') as fout:
    reader = csv.reader(fin, delimiter=";", quoting=csv.QUOTE_NONE)
    writer = csv.writer(fout, delimiter=";", quoting=csv.QUOTE_ALL)

    # skip header
    next(reader)

    buffer_ = [row[0] for row in reader]

    writer.writerow(['ID1', 'ID2'])
    writer.writerows(i for i in product(buffer_, repeat=2))

如果您需要重复次数超过2次:'ID1', 'ID2',..., 'IDn',请将product中的重复值更改为n

答案 1 :(得分:1)

由于csv.reader是文件的迭代器,因此只能进行一次。尝试将行读入列表:

with open("result.csv", "b") as f, open("distances.csv", "wb") as ff:
    reader = csv.reader(f, delimiter=";", quoting=csv.QUOTE_NONE)
    writer = csv.writer(ff, delimiter=";", quoting=csv.QUOTE_ALL)
    rows = list(reader)

    for row1 in rows:
        for row2 in rows:
            lst = row1 + row2
            writer.writerow(lst)