英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论