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.

anatol
  • 791
  • 9
  • 16
KB303
  • 143
  • 1
  • 6
  • 1
    `oneOranization.csv` or `oneOrganization.csv` ?? and check current path. also post error message, we cannot guess otherwise. – Jean-François Fabre Jul 04 '17 at 08: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). – bruno desthuilliers Jul 04 '17 at 09:01
  • traceback error message would also be helpful. – Stael Jul 04 '17 at 09: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. – KB303 Jul 04 '17 at 09:02
  • what do you get if you `print reader2` – Stael Jul 04 '17 at 09:03
  • Can you provide the content of the file and the output if you print all lines? – P. Siehr Jul 04 '17 at 09:03
  • try without `newline=''` that seems an odd thing to have there - doesn't that mean starting a new line every time it matches an empty string? What does that even do? – Stael Jul 04 '17 at 09:07
  • @Stael this is the recommended way to open files if you use them with `csv`. – Thierry Lathuille Jul 04 '17 at 09:09
  • but for reading it is not very useful. – Jean-François Fabre Jul 04 '17 at 09:11
  • @Stael, the `newline=''` means that the file is read in universal newline mode but the newline sequences are passed through to the reader unchanged. So it is indeed the recommended way to use the `csv` module and no need to open the file 'rb'. – Duncan Jul 04 '17 at 09:24
  • @Stael : When I print reader2, I get : – KB303 Jul 04 '17 at 12:21
  • @P.Siehr : The content file is a singe line : "roleAssignmentId,roleId,role,assignedTo,assignedToUser,scopeType,orgUnitId,orgUnit" I'm starting to think that reader2 is empty at that point, that would explain why it doesn't get in the loop. – KB303 Jul 04 '17 at 12:21

1 Answers1

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.

Rayhane Mama
  • 2,374
  • 11
  • 20