1

This is a code in a book.

import csv
villains = [['Doctor', 'No'],
            ['Rosa', 'Klebb'],
            ['Mister', 'Big'],
            ['Auric', 'Goldfinger'],
            ['Ernst', 'Blofeld'],
            ]
with open('villains', 'wt') as fout:
    csvout = csv.writer(fout)
    csvout.writerows(villains)
with open('villains', 'rt') as fin:
    cin = csv.reader(fin)
    villains = [row for row in cin]
print(villains)

My result is

[['Doctor', 'No'], [], 
['Rosa', 'Klebb'], [], 
['Mister', 'Big'], [], 
['Auric', 'Goldfinger'], [], 
['Ernst', 'Blofeld'], []]

Expected result is

[['Doctor', 'No'], 
['Rosa', 'Klebb'], 
['Mister', 'Big', 
['Auric', 'Goldfinger'], 
['Ernst', 'Blofeld']]

But I have some empty list in my result. I don't understand why these are appearing.

MY QUESTION

  1. What in my code makes the empty lists?

  2. How to correct my code to obtain expected result?

Thanks in advance.

0

1 Answer 1

2

The empty lines are there because the generated file contains empty lines:

Doctor,No

Rosa,Klebb

Mister,Big

Auric,Goldfinger

Ernst,Blofeld

This can be remedied by adding if row when reading the file:

with open('villains', 'r') as fin:
    cin = csv.reader(fin)
    villains = [row for row in cin if row]

print(villains)
#  [['Doctor', 'No'], ['Rosa', 'Klebb'], ['Mister', 'Big'], ['Auric', 'Goldfinger'],
#  ['Ernst', 'Blofeld']] 

Alternatively you can generate the file without blank lines by passing newline='' to open:

with open('villains', 'wt', newline='') as fout:
    csvout = csv.writer(fout)
    csvout.writerows(villains)
Sign up to request clarification or add additional context in comments.

1 Comment

What makes empty lines in the generated file? When I check the file by notepad, there is no empty line.

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.