1. 程式人生 > >python讀寫ini檔案的模組

python讀寫ini檔案的模組

使用dict4ini

Examples

Example 1 Create a ini file

import dict4ini

    x
= dict4ini.DictIni('test.ini')
    x
.common.name ='limodou'
    x
.common.bool=1
    x
.common.list =[3,1.2,'Hello','have spaces']
    x
.save()

This example will save option to test.ini. As you can see, you needn't create section "common" at first, just think it's there, it's ok. The result of test.ini is:

[common]
list
=3,1.2,Hello,"have spaces",bool=1
name
= limodou

And you can see, once the value has special chars, just like ' ', ',', '/"', etc, the string will be quoted by double quoter. But "Hello" is a single word, and it has not the special chars, so it won't be quoted. If the value is number, it'll be just like number literal, but if the value is number string, it'll be quoted by double quoter.

In this time, the Dict4Ini support int, float, list/tuple, string, unicode data type, for others you should convert yourself.

Example 2 Open an existed ini file

import dict4ini

    x
= dict4ini.DictIni('test.ini')print x.common.boolprint x.common.list
   
print x.common.name

So it's easy. The result will be:

1[3,1.2,'Hello','have spaces']
limodou

The data is auto converted to its original type.

Example 3 Dealing default values

Many times, you may want to set default values of options, once it is not set in configuration file. Using Dict4Ini, you have many ways to do that:

Using dict's setdefault() method

x = dict4ini.DictIni()
x
.test.setdefault('a','b')print x.test.a

Passing a dict to DictIni init method

d ={'test':{'a':'b'}}
x
= dict4ini.DictIni(values=d)print x.test.a

Creating config object first, then assign a dict value

x = dict4ini.DictIni()
d
={'a':'b'}
x
.test = d
print x.test.a

Example 4 Saving comments in ini file

import dict4ini
    x
= dict4ini.DictIni('test.ini')

    x
.common._comment ='This is a comment test./nThis is the second line.'
    x
.common.name ='limodou'
    x
.common.comment('name','Input your name')
    x
.common.bool=1
    x
.common.comment('bool','Boot type')
    x
.common.list =['3','Hello','have spaces']
    x
.common.comment('list','list testing')
    x
.save()

You can save comments in configuration also. Adding comments to section, you should using x.section._comment = 'comments'. Comments could be multi lines. Or you could use more commonly method, x.comment(). Just like x.comment('common', 'comments'). Add comments to options, you can only using comment() method, just like x.common.comment('list', 'comments').

The result of the ini file will be:

# This is a comment test.# This is the second line.[common]# Boot typebool=1# list testing
list
="3",Hello,"have spaces",# Input your name
name
= limodou

Example 5 Using unicode in ini file

Using default encoding

#coding=utf-8import dict4ini
x
= dict4ini.DictIni('test.ini')
x
.common.name = u'中文名'
x
.save()

Note: You should specify the coding used in the .py file. In this case is utf-8. Then I assign x.common.name with a unicode string. If you don't specify the encoding in create instance of the DictIni, the Dict4Ini will auto find the default encoding in the system in turns of:

*local.getdefaultlocale()[1]* sys.getfilesystemencoding()* utf-8*The BOM of the file

The result of the ini file will be:

[common]
name
= u"中文名"

You should notice the file encoding will be utf-8, and the name's value is like python unicode syntax. For easiness, it doesn't support using unicode in comments.

Specifying encoding name

You can also specify the encoding of ini file, just like:

#coding=utf-8import dict4ini
x
= dict4ini.DictIni('test.ini', encoding='gbk')
x
.common.name = u'中文名'
x
.save()

It's easy to set an encoding of ini file.

Example 6 Using multi section

import dict4ini
x
= dict4ini.DictIni('test.ini')
x
.common.settings.a =1
x
.common.settings.b =["3","hello"]
x
.special.name ='limodou'
x
.special.homepage ='http://www.donews.net/limodou'
x
.save()

You don't need to care if subsection is created, you need to just use it.

The result of the ini file will be:

[common/settings]
    a
=1
    b
="3",hello,[special]
    homepage
= http://www.donews.net/limodou
    name
= limodou

Example 7 Getting ordered options

Sometimes we need to keep the order or the options according to the ini file, so how to get the ordered items?

ini = dict4ini.DictIni('x.ini')for key, value in ini.ordereditems(ini):print key, value

This example is dealing with the first level section.

ini = dict4ini.DictIni('x.ini')for key, value in ini.ordereditems(ini.autostring):print key, value

This example is dealing with certain section.

Example 8 Encrypt options

You can also encrypt some specified sections if you need. The Dict4Ini ships with a p3.py module, which can be used to encrypt/decrypt.

import dict4ini

d
= dict4ini.DictIni('tt.ini', secretKey='limodou', secretSections='a')
d
.a.name ='limodou'
d
.save()

And the result will be

[a]
name
= v1ToGlTNo+YoB0VF5wk1Ea1XnRIVIv7xNNKOXSTdeA==

Here the parameter secretSections can be a string list or a string with ',' delimeter, for example: 'a,b' will be treated as 'b'. You should know all subsections of a specified section will be encrypted.

Example 8 Hide data with base64 encoding

The code is:

import dict4ini

d
= dict4ini.DictIni('tt.ini', hideData=True)
d
.a.name ='limodou'
d
.save()

And the result is:

[a]
name
= bGltb2RvdQ==

Examples waiting

FAQ

1. Can I delete an option?

A: Yes. For example:

import dict4ini
x
= dict4ini.DictIni('test.ini')del x.a
x
.save()

2. How to use 'xxx.xxx' style option key?

A: Easy. Just using dict syntax, for example:

x['common']['xxx.xxx']='a'

or

x.common['xxx.xxx']='a'

3. How to deal the key including section delimeter char, just like '/'

A: As you creating the DictIni instance, you can specify a "onelevel=True" parameter:

x = dict4ini.DictIni('inifile', onelevel=True)

But it'll not support multi section again. So you can also defined another sectiondelimeter char different from '/', just like:

x = dict4ini.DictIni('inifile', sectiondelimeter='@')

But every time you called dict4ini.DictIni() you may need including sectiondelimeter parameter.

4. Can Dict4Ini process the simple ini format

A: Yes, it can. You can just simple pass a normal parameter to DictIni class. And all value will be treated string type, and when you saving the ini file, the value will be converted to string type automatically, and in normal mode, only these types support: int, float, str, unicode(will be automatically encoded to specifial encoding). And it doesn't support multiple level sections. And you need update to 0.9.3+.

相關推薦

pythonini檔案模組

使用dict4ini Examples Example 1 Create a ini file import dict4ini    x = dict4ini.DictIni('test.ini')    x.common.name ='limodou'    x.com

菜鳥學Python(12):怎麼ini檔案

比如有一個檔案update.ini,裡面有這些內容:[ZIP]EngineVersion=0DATVersion=5127FileName=dat-5127.zipFilePath=/pub/antivirus/datfiles/4.x/FileSize=13481555Ch

(轉)用PythonExcel檔案&&幾種模組比較

關於初始化 Excel的com介面的具體細節我就不介紹了,需要的話直接查閱相關的MSDN文件即可。這裡只提幾個特殊的小問題。 要想得到一個可以操作的excel物件,一般可以有兩種方式: import win32com.client excel = win32com.client.Dispatch('Ex

python-inipythonini文件

clas edr print 代碼 cells order sta read param 【python-ini】python讀寫ini文件 本文實例講述了Python讀寫ini文件的方法。分享給大家供大家參考。具體如下: 比如有一個文件update.ini,裏面有這些

Pythontxt檔案時的編碼問題

  這個問題來自於一個小夥伴,他在處理中文資料時需要先把裡面的文字過濾然後分詞,因為裡面有許多符號,不僅是中文標點符號,還有✳,emoji等奇怪的符號。   正常情況下,中文的str經過encode('utf-8')變成bytes,然後bytes經過decode('utf-8')變回中文。   原始檔案是

C#中INI檔案的方法例子

[DllImport(“kernel32”)] private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); [DllImp

pythoncsv檔案方法總結

python提供了大量的庫,可以非常方便的進行各種操作,現在把python中實現讀寫csv檔案的方法使用程式的方式呈現出來。 1、使用csv讀寫csv檔案方法總結 reader()函式是一個閱讀器把閱讀的CSV檔案每一行以一個列表表示出來以至於你可以用for迴圈來遍歷他 讀檔案的時候,開啟檔

Python.csv檔案

# encoding: UTF-8 import csv # 讀取csv檔案 stocks_list = [] #方式一 # file = open(u'../Output.csv', u"r") # data = csv.reader(file) # 返回的是迭代型別 #方式二 with

QT QSettingsini檔案的用法

QSettings *config_write=new QSettings("eric.ini",QSettings::IniFormat); config_write->setValue("ip/first","192.168.0.1"); config_wr

pythonjson檔案[未測試]

建立json檔案: {     "fontFamily": "微軟雅黑",     "fontSize": 12,     "BaseSettings":{     

python操作txt檔案中資料教程[1]-使用pythontxt檔案

python操作txt檔案中資料教程[1]-使用python讀寫txt檔案 覺得有用的話,歡迎一起討論相互學習~Follow Me 原始txt檔案 程式實現後結果 程式實現 filename = './test/test.txt' contents = [] DNA_sequence

vbini檔案

程式碼最開頭加入這個: Private Declare Function GetPrivateProfileString Lib “kernel32” Alias “GetPrivateProfileStringA” ( _ ByVal lpApplicationName As String

PythonXML檔案

什麼是XML XML是可擴充套件標記語言(Extensible Markup Language)的縮寫,其中標記是關鍵部分。使用者可以建立內容,然後使用限定標記標記它,從而使每個單詞、短語或塊成為可識別、可分類的資訊。 標記語言從早起的私有公司和政府制定形式逐

python 壓縮檔案

  gzip 和 bz2 模組可以很容易的處理這些檔案。 兩個模組都為 open() 函式提供了另外的實現來解決這個問題。 比如,為了以文字形式讀取壓縮檔案,可以這樣做: # gzip compression impor

pythonjson檔案

JSON(JavaScript Object Notation) 是一種輕量級的資料交換格式。它基於ECMAScript的一個子集。 JSON採用完全獨立於語言的文字格式,但是也使用了類似於C語言家族的習慣(包括C、C++、Java、JavaScript、Perl、P

python配置檔案操作

1.簡介  - read(filename) 讀取ini檔案內容  - sections() 以列表形式展示所有的section  - options(section) 展示該section的optio

pythonh5檔案

原文連結:https://blog.csdn.net/leibaojiangjun1/article/details/53635353  h5接受的資料是矩陣跟mat方法一致,但是具有更強的壓縮效能 使用hdf5依賴於python的工具包:h5py import h5py &nbs

MFCini檔案方法

VC中用函式讀寫ini檔案的方法          ini檔案(即Initialization file),這種型別的檔案中通常存放的是一個程式的初始化資訊。ini檔案由若干個節(Section)組成,每個Section由若干鍵(Key)組成,每個Key可以賦相應的值。讀寫ini檔案實際上就是讀寫某個的Sec

WINCE C#INI檔案

最近開發一個CE上的GPS程式,用到配置儲存,由於資料比較少且資料結構簡單,所以採用了INI格式,WINCE沒有提供windows裡讀寫ini的函式,就自己寫了一個,程式碼如下(C#):     ///////////////////////////////////////

WIN32INI檔案方法

概述 在程式中經常要用到設定或者其他少量資料的存檔,以便程式在下一次執行的時候可以使用,比如說儲存本次程式執行時視窗的位置、大小、一些使用者設定的 資料等等,在 Dos 下程式設計的時候,我們一般自己產生一個檔案,由自己把這些資料寫到檔案中,然後在下一次執行的時候再讀出來使