从CSV文件读取特定的单元格

时间:2018-12-05 12:17:30

标签: python loops csv

我试图遍历CSV文件中的每个单元,但没有成功。为简化起见,假设我的csv文件是3x3矩阵:

8.046875    10.4375     -0.625
0.171875    4.546875    1.953125
-4.890625   -3.703125   6.359375

现在,我使用以下代码迭代单元格:

import csv


class GetData:

    def __init__(self, path):
        self.path = path

    def read_matrix(self):
        with open(self.path, 'r') as matrix:
            csv_reader = csv.reader(matrix, delimiter=',')
            for cell in csv_reader:
                cell = ', '.join(cell)
                print(cell)


test = GetData('D:/testFile_0001.ascii.csv')
test.read_matrix()

如果我运行此代码,它将打印上面显示的矩阵。 当我更改为:

print(cell[0])

输出为:

8
0
-

我的问题是: 1.为什么打印第一列中的第一位? 2.如何从此矩阵打印特定的单元格?

谢谢!

1 个答案:

答案 0 :(得分:0)

您遇到一些问题:

  1. 您的数据未用逗号分隔,但您的代码表明应使用
  2. csv.reader返回数组而不是单元格
  3. cell[0]返回一个字符的原因是因为您在执行cell时将数组cell = ', '.join(cell)转换为字符串。 'string'[0]将返回字符串的第一个字符,这就是cell[0]只给您第一个数字的原因。
  4. 我添加了read_matrix_2,它将返回您要查找的矩阵。

以下是如何访问单元格的有效示例:https://paiza.io/projects/gkwMf22jbQEb3CO9d1BHjQ?language=python

import csv


class GetData:

    def __init__(self, path):
        self.path = path

    def read_matrix(self):
        with open(self.path, 'r') as matrix:
            csv_reader = csv.reader(matrix, delimiter=',')
            for row in csv_reader:
                print row
                print ', '.join(row)
                    for i, cell in enumerate(row):
                        print "cell[{i}]={cell}".format(**locals())                    

    def read_matrix_2(self):
        with open(self.path, 'r') as matrix:
            csv_reader = csv.reader(matrix, delimiter=',')
            return [ row for row in csv_reader]




test = GetData('data.csv')
test.read_matrix()

print "This will give you a matrix"
matrix = test.read_matrix_2()
print matrix
print matrix[2][1]

data.csv

8.046875,10.4375,-0.625
0.171875 ,4.546875,1.953125
-4.890625 ,-3.703125,6.359375

输出

['8.046875', '10.4375', '-0.625']
8.046875, 10.4375, -0.625
cell[0]=8.046875
cell[1]=10.4375
cell[2]=-0.625
['0.171875 ', '4.546875', '1.953125']
0.171875 , 4.546875, 1.953125
cell[0]=0.171875 
cell[1]=4.546875
cell[2]=1.953125
['-4.890625 ', '-3.703125', '6.359375']
-4.890625 , -3.703125, 6.359375
cell[0]=-4.890625 
cell[1]=-3.703125
cell[2]=6.359375
This will give you a matrix
[['8.046875', '10.4375', '-0.625'], ['0.171875 ', '4.546875', '1.953125'], ['-4.890625 ', '-3.703125', '6.359375']]
-3.703125