avi007
avi007

Reputation: 59

write in a csv file in python and read it using the column name

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

Upvotes: 2

Views: 88

Answers (1)

BA.
BA.

Reputation: 934

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.

Upvotes: 2

Related Questions