我正在尝试编写一个精简的音乐曲目列表,它们已被播放的时间以及艺术家以表格形式写入文本文件。
然而目前的曲目是列表形式,即
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])
关于如何将数据放入表而不仅仅是列表的任何想法?
答案 0 :(得分: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