格式化输出文件

时间:2010-02-12 01:51:26

标签: python text formatting logging

我目前正在使用python索引我的音乐集。理想情况下,我希望将输出文件格式化为;

"Artist;
 Album;
             Tracks - length - bitrate - md5
Artist2;
 Album2;
             Tracks - length - bitrate - md5"

但我似乎无法弄清楚如何实现这一目标。有什么建议吗?

2 个答案:

答案 0 :(得分:1)

>>> import textwrap
>>> class Album(object):
...     def __init__(self, title, artist, tracks, length, bitrate, md5):
...         self.title=title
...         self.artist=artist
...         self.tracks=tracks
...         self.length=length
...         self.bitrate=bitrate
...         self.md5=md5
...     def __str__(self):
...         return textwrap.dedent("""
...         %(artist)s;
...         %(title)s;
...                       %(tracks)s - %(length)s - %(bitrate)s - %(md5)s"""%(vars(self)))
... 
>>> a=Album("album title","artist name",10,52.1,"320kb/s","4d53b0cb432ec371ca93ea30b62521d9")
>>> print a

artist name;
album title;
              10 - 52.1 - 320kb/s - 4d53b0cb432ec371ca93ea30b62521d9

答案 1 :(得分:1)

如果输入数据是元组列表,每个元组有6个字符串(artist, album, tracks, length, bitrate, md5)

for artist, album, tracks, length, bitrate, md5 in input_data:
  print "%s;" % artist
  print "%s;" % album
  print "            %s - %s - %s - %s" % (tracks, length, bitrate, md5)

如果您的输入数据采用不同的格式,这基本上同样容易,但除非您告诉我们输入数据的 格式,否则我们只是试着猜测是非常愚蠢的。 / p>