找到文本然后在Python中添加行

时间:2010-08-09 14:02:31

标签: python plist

我需要读取一个plist文件并搜索一个字符串,然后在下一行添加一行新文本。我无法想象这样做会花费很多。然而,plist是二进制格式,所以不确定如何处理它。

提前致谢,

亚伦

#Convert plist to XML
os.system('plutil -convert xml1 com.apple.iChat.Jabber.plist')

AutoDiscovery = "<integer>0<integer>"

import fileinput
for line in fileinput.FileInput("com.apple.iChat.Jabber.plist",inplace=1):
   line = line.replace("<key>AutoDiscoverHostAndPort</key>",AutoDiscovery)
   print line,

#Concert plist to binary file
os.system('plutil -convert binary1 com.apple.iChat.Jabber.plist')

2 个答案:

答案 0 :(得分:2)

您希望首先将其转换为xml格式:

plutil -convert xml file.plist

其余的应该相当容易。

编辑:

newFile = open('file.copy', 'w+')
for line in open('file'):
    if (line.find('string_to_find') >= 0):
        # do something with "line"
    newFile.write(line)
newFile.close()

EDIT2:

# convert plist from binary to xml

plist = plistlib.readPlist('your.plist')
plist['key'] = 0
plistlib.writePlist('your.plist')

# convert plist from xml to binary

答案 1 :(得分:0)

使用plistlib来满足您的所有plist文件需求。无需转换。