我想从数据列表中创建一个csv,但是键值在列表的各个部分之间有所不同。该列表具有以下布局:
[Game 1]
Publisher=
Developer=
Released=Nov, 2005
Systems=
Genre=Action|Strategy
Perspective=3rd-Person Perspective
Score=4.5
Controls=
Players=
Rating=
Url=http://www.google.com.pl
Description=This cartridge contains six of the 1 kilobyte e......
[Game 2]
Publisher=Home Entertainment Suppliers Pty. Ltd.
Developer=Imagic
Released=1992
Systems=
Genre=Action
Perspective=3rd-Person Perspective
Score=1.5
Controls=Joystick (Digital)|Same/Split-Screen Multiplayer
Players=1-2 Players
Rating=
Url=http://www.google.com
Description=An unlicensed multi-cart from the Australian-bas.....
Goodname=2 Pak Special - Alien Force & Hoppy
NoIntro=
Tosec=2 Pak Special Light Green - Hoppy & Alien Force
Full file here
每组数据都用[Game *]分隔,并且某些游戏中每个游戏显示的值可以为空白或不存在,例如,游戏1中缺少Goodname =,NoIntro =和Tosec =。我不知道总数所需的键/列数。理想情况下,我希望将每个游戏放在csv文件的单独一行中。
有人对如何将这种数据格式转换为csv有任何想法吗?我很困惑我对bash和python很熟悉,但是我对如何自动执行转换的任何建议都持开放态度。
提前致谢。
最佳答案
在Python中,您可以使用ConfigParser库读取INI file,并使用csv库编写以逗号分隔的文件。我在下面写了一个小脚本ini2csv.py
,您可以使用以下命令来处理转换:
cat atari.ini | ./ini2csv.py > atari.csv
这是脚本:
#!/usr/bin/python
# encoding: utf-8
import sys
import csv
from ConfigParser import ConfigParser
ini = ConfigParser()
ini.readfp(sys.stdin)
#Find all keys in the INI file to build a row template and
#include a "game" field to store the section name.
rowTemplate = {"game":""}
for sec in ini.sections():
for key,value in ini.items(sec):
rowTemplate[key] = ""
#Write the CSV file to stdout with all fields in the first line
out = csv.writer(sys.stdout)
out = csv.DictWriter(sys.stdout, fieldnames=rowTemplate.keys())
out.writeheader()
#Write all rows
for sec in ini.sections():
row = rowTemplate.copy()
row["game"] = sec
for key,value in ini.items(sec):
row[key] = value
out.writerow(row)
我使用您在问题中提供的链接对其进行了测试,它似乎可以正常工作。