Python讀寫ini檔案的方法

來源:互聯網
上載者:User

Python讀寫ini檔案的方法

   本文執行個體講述了Python讀寫ini檔案的方法。分享給大家供大家參考。具體如下:

  比如有一個檔案update.ini,裡面有這些內容:

  ?

1

2

3

4

5

6

7

8

[ZIP]

EngineVersion=0

DATVersion=5127

FileName=dat-5127.zip

FilePath=/pub/antivirus/datfiles/4.x/

FileSize=13481555

Checksum=6037,021E

MD5=aaeb519d3f276b810d46642d782d8921

  那就可以通過下面這些代碼得到MD5的值,簡單吧

  ?

1

2

3

4

5

6

7

#!/usr/bin/env python

# -*- coding: utf-8 -*-

import ConfigParser

config = ConfigParser.ConfigParser()

config.readfp(open('update.ini'))

a = config.get("ZIP","MD5")

print a

  寫也很簡單:

  ?

1

2

3

4

5

6

7

8

9

10

import ConfigParser

config = ConfigParser.ConfigParser()

# set a number of parameters

config.add_section("book")

config.set("book", "title", "the python standard library")

config.set("book", "author", "fredrik lundh")

config.add_section("ematter")

config.set("ematter", "pages", 250)

# write to file

config.write(open('1.ini', "w"))

  修改也不難(新增內容):

  ?

1

2

3

4

5

6

7

8

#!/usr/bin/env python

# -*- coding: utf-8 -*-

import ConfigParser

config = ConfigParser.ConfigParser()

config.read('1.ini')

a = config.add_section("md5")

config.set("md5", "value", "1234")

config.write(open('1.ini', "r+")) #可以把r+改成其他方式,看看結果:)

  修改內容:

  ?

1

2

3

4

5

6

7

#!/usr/bin/env python

# -*- coding: utf-8 -*-

import ConfigParser

config = ConfigParser.ConfigParser()

config.read('1.ini')

config.set("md5", "value", "kingsoft") #這樣md5就從1234變成kingsoft了

config.write(open('1.ini', "r+"))

  刪除部分就懶得寫了,感興趣的自己看文檔:

  remove_option( section, option)

  Remove the specified option from the specified section. If the section does not exist, raise NoSectionError. If the option existed to be removed, return True; otherwise return False. New in version 1.6.

  remove_section( section)

  Remove the specified section from the configuration. If the section in fact existed, return True. Otherwise return False.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.