2

while i have written this code

import csv
    with open('persons.csv', 'w') as csvfile:
        filewriter = csv.writer(csvfile, delimiter=',',quotechar='|')
        filewriter.writerow(['Name', 'Profession'])
        filewriter.writerow(['Derek', 'Software Developer'])
        filewriter.writerow(['Steve', 'Software Developer'])
        filewriter.writerow(['Paul', 'Manager'])

and i am getting the result as

['Name', 'Profession']
[]
['Derek', 'Software Developer']
[]
['Steve', 'Software Developer']
[]
['Paul', 'Manager']
[]

it is leaving a line in between. how to resolve it ???

And one more thing i want to read the data from csv using their column name i.e.

import csv
with open('persons.csv') as f:
    reader = csv.reader(f)
 
  
    for Name, Profession in reader:
        print(Name, Profession)

--when i run this code it shows error..

 for Name, Profession in reader:
ValueError: not enough values to unpack (expected 2, got 0)

please suggest how it can work

8
  • I checked your code and my csv file is correct Commented Sep 14, 2017 at 4:02
  • works ok for me too. The csv it creates is correct. It doesnt look like what you've posted. To me that output looks like the result of using print inside list comprehensions. Commented Sep 14, 2017 at 4:02
  • Please do not ask new questions by editing old questions. If you have a new question about saving as jpeg, post it as a new question. Otherwise the existing csv answer won't make any sense to future readers. Commented Jul 6, 2021 at 8:38
  • @tdy unaable to ask a new question Commented Jul 6, 2021 at 8:59
  • i see, i guess due to previous downvotes. i just upvoted both of your posts, but not sure if that will be enough to lift the restriction. Commented Jul 6, 2021 at 9:07

1 Answer 1

2

csv.writer writes \r\n into the file by default. Use the following to open the file if you are running Windows

with open('persons.csv', 'w', newline='') as csvfile:

Once you have this, the empty lines will go away

The second issue is due to the first. Since you had empty lines, reader has 0 items for those lines, and hence the exception.

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

Comments

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.