简体   繁体   English

将数据附加到CSV文件

[英]Appending data to csv file

I am trying to append 2 data sets to my csv file. 我正在尝试将2个数据集附加到我的csv文件中。 Below is my code. 下面是我的代码。 The code runs but my data gets appended below a set of data in the first column (ie col[0]). 代码运行了,但是我的数据被追加到第一列中的一组数据下面(即col [0])。 I would however like to append my data sets in separate columns at the end of file. 但是,我想将数据集附加到文件末尾的单独列中。 Could I please get advice on how I might be able to do this? 请问我如何才能做到这一点? Thanks. 谢谢。

import csv

Trial = open ('Trial_test.csv', 'rt', newline = '')
reader = csv.reader(Trial)

Trial_New = open ('Trial_test.csv', 'a', newline = '')
writer = csv.writer(Trial_New, delimiter = ',')

Cortex = []
Liver = []

for col in reader:
    Cortex_Diff = float(col[14])
    Liver_Diff = float(col[17])
    Cortex.append(Cortex_Diff)
    Liver.append(Liver_Diff)
Avg_diff_Cortex = sum(Cortex)/len(Cortex)
Data1 = str(Avg_diff_Cortex)
Avg_diff_Liver = sum(Liver)/len(Liver)
Data2 = str(Avg_diff_Liver)
writer.writerows(Data1 + Data2)


Trial.close()
Trial_New.close()

I think I see what you are trying to do. 我想我明白了您要做什么。 I won't try to rewrite your function entirely for you, but here's a tip: assuming you are dealing with a manageable size of dataset, try reading your entire CSV into memory as a list of lists (or list of tuples), then perform your calculations on the values on this object, then write the python object back out to the new CSV in a separate block of code. 我不会尝试完全为您重写函数,但是这里有个提示:假设您要处理的数据集大小可控,请尝试将整个CSV作为列表列表(或元组列表)读入内存,然后执行您对该对象的值进行计算,然后在单独的代码块中将python对象写回到新的CSV中。 You may find this article or this one of use. 您可能会发现本文本文的其中一项 Naturally the official documentation should be helpful too. 当然, 官方文档也应该有所帮助。

Also, I would suggest using different files for input and output to make your life easier. 另外,我建议使用不同的文件进行输入和输出,以使您的生活更轻松。

For example: 例如:

import csv
data = []
with open('Trial_test.csv', 'rb') as csvfile:
   reader = csv.reader(csvfile, delimiter=' ', quotechar='|')
   for row in reader:
       data.append(row)

# now do your calculations on the 'data' object.

with open('Trial_test_new.csv', 'wb') as csvfile:
   writer = csv.writer(csvfile, delimiter=' ', quotechar='|')
   for row in data:
       writer.writerow(row)

Something like that, anyway! 反正就是这样!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM