1

I'm trying to read a csv file in Python using the module csv. To do that, I use a reader variable :

 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"]

However, running the program, I realize that it does get in the loop at all although the cvs file exists and is indeed called oneOrganization.csv. What could be the reason of that ?

I'm starting in Python, usually this method works.

12
  • 1
    oneOranization.csv or oneOrganization.csv ?? and check current path. also post error message, we cannot guess otherwise. Commented Jul 4, 2017 at 8:54
  • How could we answer without having the csv file itself ? But if you're on windows, you definitly want to open the file in "rb" mode ("read binary"), and let the csv module deal with newlines. Also, beware that using relative path is brittle at best (as it will be resolved against the current working directory which can be just anything at runtime). Commented Jul 4, 2017 at 9:01
  • traceback error message would also be helpful. Commented Jul 4, 2017 at 9:01
  • Thanks for your help. Sorry it is oneOrganization.csv. Concerning the path it should be ok. There is not any error message, it just doesn't pass through the loop. Commented Jul 4, 2017 at 9:02
  • what do you get if you print reader2 Commented Jul 4, 2017 at 9:03

1 Answer 1

3

The problem that prevents your code from accessing the if loop if row['Role']==[] is because you're trying to find empty elements the wrong way.
try this instead:

Method 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"]

Method 2: provided by @Jean-François Fabre

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"]

Method 3 : "elegant one liner" - by @Jean-François Fabre

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

I tried it on a csv example that can be represented like this: (np.array form)

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

and used this code:

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'])

or with method 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'])

or method 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')

output:

1
11
no

you can refer to this topic for more informations about how to check if a "cell" is empty in a csv file.

Sign up to request clarification or add additional context in comments.

7 Comments

if row['test1']: is enough ("falsy")
OP's question was about entering the for loop. What's an if loop anyway?
@RayhaneMama I think you're right, I see why the OP thought that the loop was never entered.
elegant one liner: row_dict['Role'] = row['test1'] or "User"
@RayhaneMama :) I just saw that yesterday in a nice answer. or isn't used enough like this.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.