0

I don't understand why the code below

with open('book.csv') as f:
    reader = csv.reader(f, delimiter='\t')

    for a in reader:
        print(a)

returns empty cells too.

['username', '', '', '']
['\t\t\t\t', '', '', '']
['Name', 'Surname', '', '']
['Brian', 'Fespa', '', '']
['John', 'Mc', '', '']
['\t\t\t\t', '', '', '']
['Name', 'Surname', 'Age', 'Sex']
['Lauren', 'Fon', '15', 'F']
['Tim', 'Matthew ', '25', 'M']

My purpose is to calculate the length of the rows that have actually some data. For example, the first list ['username', '', '', ''] should return length of 1 and not 4. The second list ['\t\t\t\t', '', '', ''] should return 0 and not 4.

Any help is really appreciated. Thank you!

3
  • 3
    If it didn't include empty cells, how would you know which cells in that row actually contain data? Commented Feb 25, 2020 at 12:36
  • It returns empty cells becuase its splitting the CSV. If you dont want empty cells then you should drop them after csv reader gives you the cells. What if there is a line like '1','','2'. should this show 2 or 3 since the middle is empty, should it be dropped? Commented Feb 25, 2020 at 12:38
  • What if you had 10 columns and only one had something in one column and it chose to just give you that non-empty column as a single item... what column is it? Commented Feb 25, 2020 at 12:38

1 Answer 1

1

if you want to ignore empty cells maybe something like this will be useful, I also handled \t via re:

import csv
import re

with open('book.csv') as csv_file:
    reader = csv.reader(csv_file)
    result = [[items for items in row if items != '' and items == re.sub('\t+','\t',items)] for row in reader]

print result

the book.csv file is :

username,,,
\t\t\t\t,,,
Name,Surname,,
Brian,Fespa,,
John,Mc,,
\t\t\t\t,,,
Name,Surname,Age,Sex
Lauren,Fon,15,F
Tim,Matthew,25,M

output is :

[['username'], 
[], 
['Name', 'Surname'], 
['Brian', 'Fespa'], 
['John', 'Mc'], 
[], 
['Name', 'Surname', 'Age', 'Sex'], 
['Lauren', 'Fon', '15', 'F'], 
['Tim', 'Matthew', '25', 'M']]
Sign up to request clarification or add additional context in comments.

5 Comments

Except '\t\t\t\t' won't fail that test and still be included...
So, how can I delete the empty values within a list & empty rows?
It works! Can you "translate" the list comprehension that you used? I'm familiar with simple list comprehension syntaxes.
@JonClements is it ok now ?
@zimskiz please check it again, I removed \t\t too !

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.