Ali Tajik
Ali Tajik

Reputation: 39

write the output of the code on a CSV file

I have a csv file a list of name and mean. For example:

ali,5.0
hamid,6.066666666666666
mandana,7.5
soheila,7.833333333333333
sara,9.75
sina,11.285714285714286
sarvin,11.375

I am going to rewrite the csv by three lower mean. I have write the code, but I have a problem to write the csv again. I should keep the mean number exactly as an input.

import csv
import itertools
from collections import OrderedDict
with open ('grades4.csv', 'r') as input_file:
    reader=csv.reader(input_file)
    val1=[]
    key=list()
    threelowval=[]
    for row in reader:
        k = row[0] 
        val=[num for num in row[1:]] #seperate a number in every row 
        key.append(k) #making a name -key- list
        val1.append(val) #making a value list
        value = list(itertools.chain.from_iterable(val1)) #making a simple list from list of list in value
        value=[float(i) for i in value] ##changing string to float in values
    #print(key)
    #print(value)
    dictionary = dict(zip(key, value))
    #print(dictionary)
    findic=OrderedDict(sorted(dictionary.items(), key=lambda t: t[1])) ##making a sorted list by OrderedDict
    #print(findic)
##make a separation for the final dict to derive the three lower mean
    lv=[]
    for item in findic.values():
            lv.append(item)
    #print(lv)
    for item in lv[0:3]:
            threelowval.append(item)
    print(threelowval)

I have tried below code but I get the error.

with open('grades4.csv', 'w', newline='') as output_file_name:
    writer = csv.writer(output_file_name)
    writer.writerows(threelowval)

expected result:

5.0
6.066666666666666
7.5

Upvotes: 0

Views: 43

Answers (2)

Ali Tajik
Ali Tajik

Reputation: 39

I have tried below code and receive the correct results.

with open('grades4.csv', 'w', newline='') as output_file_name:
    writer = csv.writer(output_file_name)
    writer.writerows(map(lambda x: [x], threelowval))

Upvotes: 0

MohammadReza
MohammadReza

Reputation: 407

You should try this:

with open('grades4.csv', 'w', newline='') as output_file_name:
   writer = csv.writer(output_file_name)
   for i in threelowval:
       writer.writerow([i])

Upvotes: 2

Related Questions