Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将INI文件转换为CSV文件_Python_Bash_Csv_Export To Csv_Ini - Fatal编程技术网

Python 如何将INI文件转换为CSV文件

Python 如何将INI文件转换为CSV文件,python,bash,csv,export-to-csv,ini,Python,Bash,Csv,Export To Csv,Ini,我想从数据列表中创建一个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 cartridg

我想从数据列表中创建一个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

每组数据由[Game*]分隔,对于某些游戏,每场游戏显示的值可能为空或不存在,例如游戏1中缺少Goodname=、NoIntro=和Tosec=。我不知道所需的键/列的总数。理想情况下,我希望每个游戏在csv文件中的单独一行

有人知道如何将这种格式的数据转换成csv吗?我被难住了。我熟悉bash和python,但我愿意接受任何关于如何自动化转换的建议

提前感谢。

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

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

我将使用python,这样更容易解析配置。用于解析文件。对于每个部分,使用创建一个条目,并将不存在的值保留为空,
Game 1,,,,,,“Nov,2005”,…
PHP也可以使用.WOW来完成此操作!!在谷歌搜索了很长一段时间,甚至找不到继续下去的提示后,我认为这是没有希望的。你提供的脚本工作得非常好!非常非常感谢!:)