Python:如何从另一个csv文件向csv文件写入值

时间:2014-06-06 00:22:49

标签: python csv printing nested-loops

对于index.csv文件,其第四列有十个数字,范围从1 - 5。每个数字都可以视为一个索引,每个索引对应一个filename.csv中的数字数组。

filename.csv的行号代表索引,每行有三个数字。我的问题是使用嵌套循环将filename.csv中的数字转移到index.csv

from numpy import genfromtxt
import numpy as np
import csv
import collections

data1 = genfromtxt('filename.csv', delimiter=',')
data2 = genfromtxt('index.csv', delimiter=',')

out = np.zeros((len(data2),len(data1)))

for row in data2:

    for ch_row in range(len(data1)):

        if (row[3] == ch_row + 1):

            out = row.tolist() + data1[ch_row].tolist()

            print(out)

            writer = csv.writer(open('dn.csv','w'), delimiter=',',quoting=csv.QUOTE_ALL)

            writer.writerow(out)

例如,index.csv的第四列包含1,2,5,3,4,1,4,5,2,3filename.csv包含:

# filename.csv

20 30 50 
70 60 45 
35 26 77 
93 37 68 
13 08 55 

我需要的是将索引行从filename.csv写入index.csv并将这些数字存储在第5,第6和第7列:

# index.csv

#   4 5  6  7 
... 1 20 30 50 
... 2 70 60 45 
... 5 13 08 55 
... 3 35 26 77 
... 4 93 37 68 
... 1 20 30 50 
... 4 93 37 68 
... 5 13 08 55 
... 2 70 60 45 
... 3 35 26 77

如果我这样做"打印(输出)",它会得到正确答案。但是,当我输入" out"在shell中,只有一行显示为[1.0,1.0,1.0,1.0,20.0,30.0,50.0]

我需要的是将所有值存储在" out"变量并将它们写入dn.csv文件。

2 个答案:

答案 0 :(得分:0)

with open('dn.csv','w') as f:
    writer =  csv.writer(f, delimiter=',',quoting=csv.QUOTE_ALL)
        for row in data2:
            idx = row[3]
            out = [idx] + [x for x in data1[idx-1]]
            writer.writerow(out)

答案 1 :(得分:0)

这应该为你做的伎俩:

<强>代码:

from csv import reader, writer


data = list(reader(open("filename.csv", "r"), delimiter=" "))

out = writer(open("output.csv", "w"), delimiter=" ")

for row in reader(open("index.csv", "r"), delimiter=" "):
    out.writerow(row + data[int(row[3])])

<强> index.csv:

0 0 0 1
0 0 0 2
0 0 0 3

<强> filename.csv:

20 30 50
70 60 45
35 26 77
93 37 68
13 08 55

这会产生输出:

0 0 0 1 70 60 45
0 0 0 2 35 26 77
0 0 0 3 93 37 68

注意:这里没有必要使用numpy。标准库csv模块将为您完成大部分工作。

我还必须稍微修改您的样本数据集,因为您在filename.csv中显示的索引超出了样本数据的范围。

请注意,Python(与大多数语言一样)使用第0个索引。因此,您可能必须使用上述代码来完全满足您的需求。