Python Forum
how can I write my function output on CSV file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
how can I write my function output on CSV file
#1
how can I update CSV file ?

I have a list of name as a csv file, I read it and calculate the mean of them. finally I am going to add (name, mean) to the first csv file.
Reply
#2
check csv module https://docs.python.org/3/library/csv.html
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
here is my csv code:

Quote:mandana,5,7,3,15
hamid,3,9,4,20,9,1,8,16,0,5,2,4,7,2,1
sina,19,10,19,6,8,14,3
sara,0,5,20,14
soheila,13,2,5,1,3,10,12,4,13,17,7,7
ali,1,9
sarvin,0,16,16,13,19,2,17,8


and I am going to calculate the mean of every list in csv and add the name and mean to the csv file.

import csv
from statistics import mean

import csv
from statistics import mean

with open ('grades.csv', 'r') as input_file_name:
    reader=csv.reader(input_file_name)
    lastrow=[]
    for row in reader:
        #print (row)
        name = row[0]
        these_grades=list()
        
        for grade in row[1:]:
            #print(grade)
            these_grades.append(int(grade))
            #print(name,grade,these_grades)
            
        print(name, mean(these_grades))
with open('grades.csv', 'w', newline='') as output_file_name:
    writer = csv.writer(output_file_name)
    writer.writerows(name )
    writer.writerows(mean )
Reply
#4
because you want to overwrite the same file (is it a good idea?) you need to read the data from input file, calculate mean, store data in some data structure in memory and after you process all data - write to a file with same name.

import csv
from statistics import mean
 
with open ('grades.csv', 'r') as input_file:
    reader=csv.reader(input_file)
    data = []
    for row in reader:
        name = row[0]
        grades=[int(num) for num in row[1:]] # alternatively use: grades = map(int, row[1:])
        row.append(mean(grades))
        # alternatively use: row.append(f'{mean(grades):.2f}')
        data.append(row)

with open('grades.csv', 'w', newline='') as output_file_name:
    writer = csv.writer(output_file_name)
    writer.writerows(data)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
thanks for your answer.
how can I update csv file with mean output results in new line.

actually the correct output result would be as below:
Quote:mandana,7.5
hamid,6.066666666666666
sina,11.285714285714286
sara,9.75
soheila,7.833333333333333
ali,5.0
sarvin,11.375

so i replaced the 11 line with below line:
 row.append(float(mean(grades)))
Reply
#6
change lines 9-10 - instead of appending to row, just append to data new list with just name an mean
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#7
I dont get your point! can you explain more on the code?

and one more question, how can I make a dictionary from the name and the mean output.

name:keys and the mean:values
Reply
#8
on line 9 I add mean to existing row - you don't need this
you need to create a list with two elements - name from row and mean
then append this new list to data
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#9
so you mean that I make a new row instead of appending the existing one with the new list?
the new list should be contain a name and mean?

import csv
from statistics import mean
  
with open ('grades.csv', 'r') as input_file:
    reader=csv.reader(input_file)
    data = []
    l2=[]
    for row in reader:
        name = row[0]
        grades=[int(num) for num in row[1:]] # alternatively use: grades = map(int, row[1:])
        l2.append(name)
        l2.append(float(mean(grades)))
        
        data.append(l2)

with open('grades.csv', 'w', newline='') as output_file_name:
    writer = csv.writer(output_file_name)
    writer.writerows(data)
the output repeat the result for every line !
Reply
#10
you need to reset l2 for every row
import csv
from statistics import mean
   
with open ('grades.csv', 'r') as input_file:
    reader=csv.reader(input_file)
    data = []
    for row in reader:
        l2 = []
        name = row[0]
        grades=[int(num) for num in row[1:]] # alternatively use: grades = map(int, row[1:])
        l2.append(name)
        l2.append(float(mean(grades)))
        data.append(l2)
        # or just as a single line
        # data.append([row[0], float(mean(grades))])
 
with open('grades.csv', 'w', newline='') as output_file_name:
    writer = csv.writer(output_file_name)
    writer.writerows(data)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Last record in file doesn't write to newline gonksoup 3 404 Jan-22-2024, 12:56 PM
Last Post: deanhystad
  write to csv file problem jacksfrustration 11 1,500 Nov-09-2023, 01:56 PM
Last Post: deanhystad
  python Read each xlsx file and write it into csv with pipe delimiter mg24 4 1,427 Nov-09-2023, 10:56 AM
Last Post: mg24
  problem in output of a function akbarza 9 1,178 Sep-29-2023, 11:13 AM
Last Post: snippsat
  How do I read and write a binary file in Python? blackears 6 6,493 Jun-06-2023, 06:37 PM
Last Post: rajeshgk
  Reading data from excel file –> process it >>then write to another excel output file Jennifer_Jone 0 1,088 Mar-14-2023, 07:59 PM
Last Post: Jennifer_Jone
  Read text file, modify it then write back Pavel_47 5 1,584 Feb-18-2023, 02:49 PM
Last Post: deanhystad
  Better way to write this function SephMon 1 810 Feb-08-2023, 10:05 PM
Last Post: Gribouillis
  how to read txt file, and write into excel with multiply sheet jacklee26 14 9,893 Jan-21-2023, 06:57 AM
Last Post: jacklee26
  How to print the output of a defined function bshoushtarian 4 1,278 Sep-08-2022, 01:44 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020