使用模块csv在Python中读取csv文件

时间:2017-07-04 08:53:21

标签: python loops csv module

我正在尝试使用模块csv在Python中读取csv文件。 为此,我使用读者变量:

 with open('oneOrganization.csv', 'r', newline='') as csvfile2:
    reader2 = csv.DictReader(csvfile2, delimiter=',')

    for row in reader2:
        if row["role"] == []:
            row_dict['Role'] = "User"
        else:
            row_dict['Role'] = row["role"]

然而,运行程序时,我意识到尽管cvs文件存在,但它确实被称为oneOrganization.csv。可能是什么原因?

我从Python开始,通常这种方法有效。

1 个答案:

答案 0 :(得分:3)

阻止您的代码访问if循环if row['Role']==[]的问题是因为您试图以错误的方式查找空元素。
试试这个:

方法1:

with open('oneOrganization.csv','r') as file:
    reader = csv.DictReader(file,delimiter=',')
    my_list = list(reader)
    for row in reader:
        if row['test1'] in (None,''): # to check if cell is empty
            row_dict['Role'] = "User"
        else:
            row_dict['Role'] = row["role"]

方法2:由@ Jean-FrançoisFabre提供

with open('oneOrganization.csv','r') as file:
    reader = csv.DictReader(file,delimiter=',')
    for row in reader:
        if not row['test1']:
            row_dict['Role'] = "User"
        else:
            row_dict['Role'] = row["role"]

方法3:“优雅的一个班轮” - 来自@ Jean-FrançoisFabre

with open('oneOrganization.csv','r') as file:
    reader = csv.DictReader(file,delimiter=',')
    for row in reader:
        row_dict['Role'] = row["role"] or "User"

我在一个可以这样表示的csv示例上尝试过:(np.array form)

[['test1' 'test2' 'test3']
 [   1       2       3   ]
 [   11      22      33  ]
 [           222     333]]

并使用此代码:

import csv

with open('test_csv.csv','r') as file:
    reader = csv.DictReader(file,delimiter=',')
    for row in reader:
        if row['test1'] in (None,''):
            print('no')
        else:
            print(row['test1'])

或方法2:

import csv

with open('test_csv.csv','r') as file:
    reader = csv.DictReader(file,delimiter=',')
    for row in reader:
        if not row['test1']:
            print('no')
        else:
            print(row['test1'])

或方法3

import csv

with open('test_csv.csv','r') as file:
    reader = csv.DictReader(file,delimiter=',')
    for row in reader:
        print(row['test1'] or 'no')

输出:

1
11
no

您可以参考此topic以获取有关如何检查csv文件中“单元格”是否为空的更多信息。