【问题标题】:How to convert an INI file into an CSV file如何将 INI 文件转换为 CSV 文件
【发布时间】:2016-06-05 07:23:37
【问题描述】:

我想从数据列表创建一个 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 解析您的文件。对于每个部分,使用CSV Module 创建一个条目,并将不存在的值留空,Game 1,,,"Nov, 2005", ...
  • PHP 也可以使用parse_ini_file() 来做到这一点。

标签: python bash csv export-to-csv ini


【解决方案1】:

在 Python 中,您可以使用 ConfigParser 库来读取 INI filecsv 库来编写逗号分隔的文件。我在下面写了一个小脚本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)

我使用您在问题中提供的链接对其进行了测试,它似乎按预期工作。

【讨论】:

  • 哇!!在谷歌搜索了很长时间之后甚至没有找到继续的提示,我认为这是没有希望的。您提供的脚本效果非常好!非常感谢! :)
猜你喜欢
  • 1970-01-01
  • 2020-07-17
  • 2013-06-23
  • 2021-12-28
  • 2013-11-17
  • 2014-03-13
  • 2020-01-13
  • 2011-11-26
  • 1970-01-01
相关资源
最近更新 更多