0

我正在尝试将音乐曲目、播放时间和艺术家的简明列表以表格形式写入文本文件。

然而目前曲目是列表形式,即

08:04:10 Current Track Playing = Skinny Genes - Eliza Doolittle 

08:07:09 Current Track Playing = Keep On Walking - Scouting For Girls 

08:10:45 Current Track Playing = Thinking of Me - Olly Murs 

08:14:01 Current Track Playing = Hangin' On A String - Loose Ends 

08:17:34 Current Track Playing = Together Again - Janet Jackson 

在整个文本文件中。

我的代码看起来像这样

open('log','w').writelines([(line[:33]+line[42:])
    for line in open(fl) if "Current Track Playing" in line])

关于如何将数据放入表格而不仅仅是列表的任何想法?

4

1 回答 1

1

用于csv.writer将 CSV 样式的数据写入文件。

例子:

import csv
import re

pattern = re.compile('([0-9]*:[0-9]*:[0-9]*) Current Track Playing = ([^-]*?) - ([^-]*)$')

csv_file = open('music.csv', 'wb')
csv_writer = csv.writer(csv_file,
                        delimiter=';',
                        quotechar='"',
                        quoting=csv.QUOTE_MINIMAL)

with open('music.log', 'r') as music_log:
    for line in music_log:
        timestamp, song, artist = pattern.match(line.strip()).groups()
        csv_writer.writerow([timestamp, song, artist])

csv_file.close()

(这假设您已经从您在另一个问题中询问的日志中删除了数字 ID)。

输出:

08:04:10;Skinny Genes;Eliza Doolittle
08:07:09;Keep On Walking;Scouting For Girls
08:10:45;Thinking of Me;Olly Murs
08:14:01;Hangin' On A String;Loose Ends
08:17:34;Together Again;Janet Jackson
于 2013-08-07T16:01:56.133 回答