[英]writing csv output python
I need to take a csv file that looks like this... 我需要一个看起来像这样的csv文件......
Name,Price1,Price2,Date1,Date2
ABC,1000,7500,5/1,6/1
DEF,3000,500,5/1,7/1
GHI,5000,3500,6/1,8/1
and write it out to another csv file to make it look like this... 并将其写入另一个csv文件,使其看起来像这样......
Name,May,June,July,August
ABC,7500,1000, ,
DEF,500, ,3000
GHI, ,3500, ,5000
the spaces are suppose to be blank because nothing goes there and this is the code that I have so far 空间被认为是空白的,因为没有任何东西去那里,这是我到目前为止的代码
import csv
with open('test-data.csv','rb') as f:
csv_file=csv.reader(f)
data=[row for row in csv_file]
with open('csv-out.csv', 'wb') as out:
writer=csv.writer(out)
writer.writerow(['Name','May','June','July','August'])
for row in data:
writer.writerow(row[0])
I am new to python and I am not really sure how to use the cvs module. 我是python的新手,我不确定如何使用cvs模块。 I was thinking of making an array and just match the numbers to the months. 我正在考虑制作一个阵列,并将数字与数月相匹配。 Since price1 goes with date2 and price2 goes with date1. 由于price1与date2相同而price2与date1相同。 Am I just over thinking this? 我只是在想这个吗? I was searching around and maybe use datetime also to connect the month number to the month name. 我正在四处搜索,也可能使用datetime将月份号码连接到月份名称。 Any help or guidance is appreciated!Thanks again! 任何帮助或指导表示赞赏!再次感谢!
Edit: 编辑:
Would it be hard if I want to also add some numbers from a column like 如果我还想从列中添加一些数字,那会难吗?
Name,May,June,July,August
ABC,7500,1000, ,
DEF,500, ,3000
GHI, ,3500, ,5000
Total,8000,4500,3000,5000
Something like this should work for your question: 这样的事情应该适合你的问题:
import csv
import calendar
from collections import defaultdict
months = [calendar.month_name[i] for i in range(0, 13)]
totals = defaultdict(int)
with open("data.csv", "r") as inf, open("data-out.csv", "w") as ouf:
reader = csv.DictReader(inf)
writer = csv.DictWriter(ouf, ['Name'] + months[5:9])
writer.writeheader()
for row in reader:
m1 = months[int(row['Date1'].split('/')[0])]
p2 = int(row['Price2'])
totals[m1] += p2
m2 = months[int(row['Date2'].split('/')[0])]
p1 = int(row['Price1'])
totals[m2] += p1
writer.writerow({'Name': row['Name'], m1: p2, m2: p1})
totals['Name'] = 'Total'
writer.writerow(totals)
with open("data-out.csv", "r") as f:
print(f.read())
Name,May,June,July,August
ABC,7500,1000,,
DEF,500,,3000,
GHI,,3500,,5000
Total,8000,4500,3000,5000
If your Date#
's span the entire year you can change: 如果您的Date#
跨越整年,您可以更改:
writer = csv.DictWriter(ouf, ['Name'] + months[5:9])
to 至
writer = csv.DictWriter(ouf, ['Name'] + months[1:])
From what it looks like you want to do a column shift. 从它看起来你想要做一个列移位。 That is actually quite difficult with some libraries but the one below should be quite helpful. 对于一些图书馆来说这实际上是相当困难的,但下面的图书馆应该非常有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.