Python导出到Csv

时间:2017-12-09 06:07:30

标签: python export-to-csv

这是我正在使用的data(样本):

('Bouwmeester', [(0, 37), (155, 194), (327, 420), (541, 602), (654, 717), (761, 834), (1001, 1052), (0, 27), (79, 119), (405, 460), (546, 624), (750, 798), (834, 897), (1061, 1139), (0, 33), (170, 204), (289, 328), (447, 498), (575, 576), (729, 766), (962, 995), (1073, 1113), (1163, 1200)])
('Schwartz', [(0, 40), (165, 209), (362, 417), (550, 567), (761, 809), (881, 954), (1052, 1113), (27, 54), (195, 295), (482, 546), (707, 757), (906, 1003), (1080, 1126), (0, 33), (145, 229), (353, 408), (492, 561), (576, 640), (736, 766), (820, 870), (1094, 1163)])
('Foligno', [(0, 40), (176, 209), (362, 416), (552, 567), (761, 835), (883, 954), (459, 502), (546, 583), (757, 826), (1189, 1200), (0, 33), (212, 249), (353, 413), (575, 576), (696, 722), (722, 762)])

这是我到目前为止的Script

import csv
from itertools import combinations, product

#Header = LastName  StartTime  EndTime  Duration Period TeamAbbrev Position

#Import Game
with open('2017020397.csv', newline='') as f:
    next(f)
    skaters = '\n'.join(' '.join(row) for row in csv.reader(f))
    data = skaters.splitlines()

def to_secs(ms):
    ''' Convert a mm:ss string to seconds '''
    m, s = map(int, ms.split(':'))
    return 60 * m + s

# Store a list of (start, end) times for each player
players = {}
for row in data:
    name, start, end = row.split(None, 3)[:3]
    times = to_secs(start), to_secs(end)
    players.setdefault(name, []).append(times)

for t in players.items():
    print(t)

outfile = open("ShiftData.csv","a",newline='')
writer = csv.writer(outfile)
writer.writerow(["Player","Shift1"])
writer.writerow([name, times])
outfile.close()

输出:

Player  Shift1
Dumba   (39, 39)

output是最后一个数据,而不是整个文件。此外,我希望所有转变为output的{​​{1}}。 cell

Example:

2 个答案:

答案 0 :(得分:1)

主要问题是你只在标题后面写了一行:

writer.writerow([name, times])

相反,您需要编写数据的每个行,您可以在第二个for循环中执行此操作。

您还需要通过查找玩家次数列表的最大长度来计算出有多少Shift#列。这可以通过使用循环或内置max函数来完成:

# the loop way
shift_count = 0
for times in players.values():
    if len(times) > shift_count:
        shift_count = len(times)

# the quicker built-in way
shift_count = max(
    len(shift_times) for shift_times in players.values()
)

# then make the column names
shift_cols = [
    "Shift{}".format(num) for num in range(1, shift_count + 1)
]

将这两者放在一起:

# Move the file prep above the loop
outfile = open("ShiftData.csv","a",newline='')
writer = csv.writer(outfile)

shift_count = max(
    len(shift_times) for shift_times in players.values()
)

shift_cols = [
    "Shift{}".format(num) for num in range(1, shift_count + 1)
]

writer.writerow(["Player"] + shift_cols)

for t in players.items():
    print(t)

    row = [
        t[0],  # the first column is the player's name
    ]
    row += t[1]  # then all of the shift times next to it

    writer.writerow(row)

outfile.close()

答案 1 :(得分:0)

你需要为你想要的每一行调用一个writerow,每个玩家都需要一次。您可以循环执行以下操作:

with open('Shiftdata.csv', 'w') as out:
    writer = csv.writer(out)
    header_cells = ["Player"]
    number_of_shifts = 10
    for shift_num in range(1, number_of_shifts + 1):
        header_cells.append("Shift{}".format(shift_num))
    writer.writerow(header_cells)
    for player, shifts in players.items():
        cells = [player]
        cells.extend(shifts)
        writer.writerow(cells)