Python列表操作与日期和列

时间:2013-11-12 18:01:22

标签: python csv python-3.x

我有一个创建为XML文件的列表,看起来有点像这样:

Jun-30
12036
12345
12535
200
123135
151646
415158
Jul-1
1284646
55464
54645
8464
546544
4654658

我试图让python循环遍历这样的列表并将其转换为CSV友好格式,日期位于每列的顶部。我似乎无法让它识别日期或转换列中的金额。

1 个答案:

答案 0 :(得分:0)

因此,您的程序需要采取的步骤是一次读取一行文件,通过检测新日期将其分组到列中,然后需要将这些列转换为行并使用CSV模块写入那些行退出。

以下是一些代码:

import csv
import fileinput
import sys

# We need to collect all the columns.
columns = []
# We will be collecting one column at a time.
column = []
# Iterate over the input file(s) a line at a time.
for line in fileinput.FileInput():
    # If this line holds a date, start a new column.
    if column and not line[0].isdigit():
        columns.append(column)
        column = []

    # No matter what the line holds we need to save it to the current column.
    column.append(line.strip())

# We need to capture the last column too.
columns.append(column)

# Transpose the columns into rows.
rows = zip(*columns)
# Write out the rows as a CSV.
writer = csv.writer(sys.stdout)
writer.writerows(rows)

像这样运行:

python code.py in.txt > out.csv