python CSV writer-格式化 [英] python CSV writer - formatting
问题描述
关于如何使用python csv模块将数据正确写回CSV文件的快速问题.目前,我正在导入文件,使用datetime模块提取一列日期并创建days_of_the_week列.然后,我想写出一个包含一个原始元素和新元素的新csv文件(或覆盖单个文件).
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))
输入文件如下:
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
如果我将out_file.write中的定界符更改为逗号,则每列只会得到一个数据元素,就像这样:
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!
推荐答案
似乎您希望在第0列中输入Friday
并在第1列中输入时间,因此您需要将incoming
更改为列表列表.这意味着append语句应如下所示:
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])
...
然后,最好使用csv.writer
写回文件.您可以一次性编写整个incoming
,而不必担心格式.
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)
这篇关于python CSV writer-格式化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!