zoukankan      html  css  js  c++  java
  • python .plist 文件读写

    在开发IOS下程序的时候因为常常使用plist(属性表文件)配置一些数据,当数据多的时候手工修改特定一项数值必然是一个枯燥无聊的体力活,下面介绍如何使用python读取plist文件并且进行修改保存的。

    1、安装 python下的plist库--biplist 和简单使用

    在终端下:

    applematoMacBook-Pro:~ apple$ sudo easy_install biplist 

    完成安装之后,编写简单写入plist和读取plist的文件代码

    1)写入一个plist

    #!/usr/bin/python
    # -*- coding:utf-8 -*-
    from biplist import *
    from datetime import datetime
    plist ={ 'aKey':'aValue',
    '0':1.322,
    'now':datetime.now(),
    'list':[1,2,3],
    'tuple':('a','b','c'),
    'dict':{'list':1234,'aKey':11111}    
    }
    
    try:
        writePlist(plist,"demo.plist")
    except (InvalidPlistException,NotBinaryPlistException), e:
        print "Something bad happened:",e
    else:
        pass
    finally:
        pass
    from biplist import *  #导入biplist库

    plist ={ 'aKey':'aValue', #构建下一个字典
    '0':1.322,
    'now':datetime.now(),
    'list':[1,2,3],
    'tuple':('a','b','c'),
    'dict':{'list':1234,'aKey':11111}    
    }  

    writePlist(plist,"demo.plist")#调用biplist的writePlist进行保存,对应plist保存在当前python脚本同一目录下.

    2)读取一个plist
     1 #!usr/bin/python
     2 # -*- coding:utf-8 -*-
     3 from biplist import *
     4 
     5 try:
     6     plist = readPlist("demo.plist");
     7     print plist
     8     print plist['list'];
     9     dictlist=plist['dict'];
    10     print dictlist['aKey'];
    11     
    12 except InvalidPlistException, e:
    13     print "Not a Plist or Plist Invalid:",e
      plist = readPlist("demo.plist");#调用biplist库的readPlist函数,返回的是一个字典
      print plist['list']; #打印出list键对应的数组

     dictlist=plist['dict']; #获取dict对应的字典
    print dictlist['aKey']; #打印字典内的aKey数据
    2、修改plist

     1 #!usr/bin/python
     2 # -*- coding:utf-8 -*-
     3 from biplist import *
     4 
     5 try:
     6     plist = readPlist("demo.plist");
     7     print plist
     8     print plist['dict'];
     9     dictlist=plist['dict'];
    10     print dictlist['aKey'];
    11     
    12 except InvalidPlistException, e:
    13     print "Not a Plist or Plist Invalid:",e
    14 
    15 #修改plist
    16 dictlist['aKey']=33333;
    17 dictlist['list']=22222;
    18 
    19 try:
    20     writePlist(plist,"demo.plist")
    21 except (InvalidPlistException,NotBinaryPlistException), e:
    22     print "Something bad happened:",e
     #修改plist
    dictlist['aKey']=33333;
    dictlist['list']=22222;
    对指定的字典修改,然后保存。writePlist(plist,"demo.plist") 这时修改后plist会覆盖掉原有的那个demo.plist文件。

    3.疑问
    在使用biplist的过程中如果.plist中有中文时,修改后保存出现内容是乱码(XCode中查看源码方式),但是数据本身格式是正常。不知到有朋友可以解释吗。



     
     
  • 相关阅读:
    《Java多线程编程核心技术》——多线程与同步
    《垃圾回收的算法与实现》——Python垃圾回收
    命令提示符
    clip
    explorer
    dotnet 命令启动报错
    Superfetch/SysMain
    Windows
    Windows 系统授权服务信息
    Windows 命令
  • 原文地址:https://www.cnblogs.com/kaisne/p/biplist.html
Copyright © 2011-2022 走看看