可以用 Python 将 OrderDict 写入 CSV 表格吗?

huangapple go评论99阅读模式
英文:

can I write to CSV form orderdict in python

问题

下面是您代码的翻译部分:

什么是我的以下代码的问题
错误提示说它不可写

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))

我需要数据写入CSV文件中
英文:

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

答案1

得分: 0

以下是您要翻译的内容:

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()

希望这对您有所帮助。

英文:

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

答案2

得分: 0

通过阅读open()函数的文档,我找到了问题。需要在open函数中指定写入模式。当我添加了写入模式"w"来写入文件时,问题得以解决。

英文:

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.

huangapple
  • 本文由 发表于 2023年3月9日 19:52:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75684231.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定