2014-10-16 39 views
0

我是一名Python初學者。 所以可能是我重複相同的東西。在python中讀取一個配置文件將它存儲到一個列表中,然後將其分割成子列表

這裏問題消失 - > 我有一個名爲 installer_data.txt(包含)一個配置文件

host_ip = 10.5.5.81 
services = mesos_master,hdfs_datanode,storm,kafka,zookeeper,pig 
host_ip = 10.6.4.31 
services = mesos_slave,zookeeper,cassandra,hdfs_namenode 

我想通過這個腳本來存儲內容 - >

in_file = open("installer_data.txt","r") 
lines = [line.rstrip('\n') for line in open("installer_data.txt")] 
service_types =("mesos_master","mesos_slave","hdfs_namenode","hdfs_datanode","kafka","zookeeper","cassandra","pig") 
service = [ f for f in lines if f in service_types] 
hosts = [ f for f in lines if f not in service_types] 
print service[0] 

錯誤

Returns Traceback (most recent call last): 
    File "./file_test.py", line 13, in <module> 
    print service[0] 
IndexError: list index out of range 

由於服務列表不填充。 你們可以指點我在這裏失蹤了嗎?

+0

你希望輸出什麼? – 2014-10-16 16:05:48

+0

@bobd,你決定配置文件嗎?如果是的話,你可能想看看https://docs.python.org/2/library/configparser.html或https://pypi.python.org/pypi/configobj/5.0.6 – Werner 2014-10-16 16:09:28

+0

我期待着兩個名單Vishnu ; service_type = ['mesos_master','mesos_slave','hdfs_namenode','hdfs_datanode','kafka','zookeeper','cassandra','pig']和hosts = ['10.5.5.81','10.x。 ..',..'] – bobd 2014-10-16 16:15:57

回答

1

您可以使用regular expressions來解析它,它更容易!

import re #import regex 
string = open("data.txt","r").read() #load file 
regex = re.compile('(.+) = (.+)').findall(string) #look for pattern (.+) = (.+) in 'string' 
print regex #print 

這將輸出:

[('host_ip', '10.5.5.81'), ('services', 'mesos_master,hdfs_datanode,storm,kafka,zookeeper,pig'), ('host_ip', '10.6.4.31'), ('services', 'mesos_slave,zookeeper,cassandra,hdfs_namenode')] 

您也可以將其轉換爲一個字典,這將使它更好,但監守你有文件同名的變量,它不能是完成。無論如何,如果你想改變它,您將用它來快譯通:dict(regex),這將輸出:{'services': 'mesos_slave,zookeeper,cassandra,hdfs_namenode', 'host_ip': '10.6.4.31'}

使用字典是更好的監守,您可以通過訪問任何變量,例如:regex["host_ip"]。當您使用清單時,您只能使用數字(regex[0])訪問,如果您不知道不能使用的訂單。

+0

正則表達式片段是否適用於較老的Python 2.6.6?正如我得到正則表達式='re.compile('(。+)=(。+)') formatted_lines = regex.findall(lines) Traceback(最近呼叫最後): 文件「」,第1行,in TypeError:期望的字符串或緩衝區 – bobd 2014-10-16 16:56:09

+0

@bobd糟糕!忘了你正在使用pytyhon 3.x.我用Python 2.7寫了這個。我幾分鐘後更新了3.x版本的代碼.. – ohad987 2014-10-16 17:07:20

+0

@ ohad987 - 不,不,我正在使用一個相當老的Python 2.6.6 :( – bobd 2014-10-16 17:12:21

相關問題