python csv writer,python CSV writer-格式化

Quick question on how to properly write data back into a CSV file using the python csv module. Currently i'm importing a file, pulling a column of dates and making a column of days_of_the_week using the datetime module. I want to then write out a new csv file (or overright the individual one) containing one original element and the new element.

with open('new_dates.csv') as csvfile2:

readCSV2 = csv.reader(csvfile2, delimiter=',')

incoming = []

for row in readCSV2:

readin = row[0]

time = row[1]

year, month, day = (int(x) for x in readin.split('-'))

ans = datetime.date(year, month, day)

wkday = ans.strftime("%A")

incoming.append(wkday)

incoming.append(time)

with open('new_dates2.csv', 'w') as out_file:

out_file.write('\n'.join(incoming))

Input files looks like this:

2017-03-02,09:25

2017-03-01,06:45

2017-02-28,23:49

2017-02-28,19:34

When using this code I end up with an output file that looks like this:

Friday

15:23

Friday

14:41

Friday

13:54

Friday

7:13

What I need is an output file that looks like this:

Friday,15:23

Friday,14:41

Friday,13:54

Friday,7:13

If I change the delimiter in out_file.write to a comma I just get one element of data per column, like this:

Friday 15:23 Friday 14:41 Friday 13:54 ....

Any thoughts would be appreciated. Thanks!

解决方案

It seems you want Friday in column 0 and the time in column 1, so you need to change your incoming to a list of lists. That means the append statement should look like this:

...

incoming.append([wkday, time])

...

Then, it is better to use the csv.writer to write back to the file. You can write the whole incoming in one go without worrying about formatting.

with open('new_dates2.csv', 'w') as out_file:

writer = csv.writer(out_file)

writer.writerows(incoming)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值