tags:

views:

98

answers:

2

Hello,

I need to read a plist file and search for a string, then add a new line of text on the next line. I can't imagine it will take much to do this. However the plist is in binary format so not exactly sure how to deal with that.

Thanks in advance,

Aaron

#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')
A: 

Use plistlib for all your plist file needs. No conversion needed.

nosklo
Does plistlib support binary plists?
Georg
I figured out how to use plutil to convert to xml and the back to binary. What I'm still having troubles with is, finding a string in the file and adding a new line of text on the following line.
Aaron
+1  A: 

You want to convert it into xml format first:

plutil -convert xml file.plist

Then the rest should be fairly easy.

EDIT:

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
William
Thanks, I just figured this out to convert to xml and back. I'm not sure however how to find the string of text and add a new line of text after. Are you familiar with this?
Aaron
Sorry I'm not the best with python. I assume I need to write something under the if statement but not sure how to make it write after the string that is found. Specifically, i just need to write <integer>1</integer> after the 'string_to_find'
Aaron
You could try a bit harder to find out the solution yourself: http://rgruet.free.fr/PQR25/PQR2.5.html
William
Okay, thanks for the help. So far this is what I have (see above). Is there a way to use the replace so that it replaces the line below what I'm asking it to find?
Aaron
With your current approach, you could simply use a flag: e.g. set lineFound = true, and catch the flag on the next line. But it is probably more elegant to use plistlib after you have converted the plist to xml. E.g. (see above)
William
How would I catch the flag on next line? I guess I'm just not so certain on how to edit the following line once I've found "<key>AutoDiscoverHostAndPort</key>" in this case.
Aaron
You may need to read about "flag-controlled loops": http://www.ada95.ch/doc/tut1/Loops/control.html
William