0

what is the problem with my below code the error said that is not writeable

with open('F:\learning\coding\python learning\jadi excersisse\work with files\grades_for_exercise.csv') as f:
        myFile=csv.reader(f)
        person_mean=OrderedDict()
        for row in myFile:
            name=row[0]
            person_grades=[]
            for number in row[1:]:
                person_grades.append(int(number))
            person_mean[name]=mean(person_grades)
        print(list(person_mean.items()))
with open ('F:\learning\coding\python learning\jadi excersisse\work with files\one_result.csv') as csvfile:
        csvwriter=csv.writer(csvfile)
        csvwriter.writerows((person_mean))

i need the data be witten in csv file

buran
  • 13,682
  • 10
  • 36
  • 61
Yaucer
  • 3
  • 4

2 Answers2

0

From what i understand this is how you read and write csv fiels in python

import csv

data = [["a", "b", "c"], ["d", "e", "f"]]

def save_in_csv(data):
    with open("your_csv_file.csv", "w", newline="") as f:
        writer = csv.writer(f)
        writer.writerows(data)

def open_csv():
    with open("your_csv_file.csv", "r") as f:
        reader = csv.reader(f)
        for row in reader:
            print(row)

save_in_csv(data)
open_csv()

i hope this helps you

Gustje04
  • 1
  • 1
  • what kind of data can i use in writer.writerrows(data) ? – Yaucer Mar 10 '23 at 11:02
  • writerows cann write a list of rows and a row is a list in it self. for more detail you can have a look in the doc off the module because they descripe it far better then i am. Link to the docs: [link](https://docs.python.org/3/library/csv.html) – Gustje04 Mar 11 '23 at 15:09
0

By reading the document of open () function, I have found the problem. It is necessary to write the mode in open function. When I added the mode "w" for write in to the file, the problem was solved.

Yaucer
  • 3
  • 4
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 16 '23 at 05:13