Python版本:2.7
Test.py和aliyun.ini处于同一目录下。


Aliyun.ini内容

1
2
3
[Credentials]
accesskeyid = $accesskeyid
accesskeysecret = $accesskeysecret

Test.py

1
2
3
4
5
6
7
8
9
10
11
#!/usr/bin/python
# -*- coding:utf-8 -*-
import time,ConfigParser,os
CONFIGFILE = os.getcwd() + '\\aliyun.ini' #win的版本需要添加\
with open(CONFIGFILE,'r') as f1:
print f1.readlines()
timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
config = ConfigParser.ConfigParser()
config.read(CONFIGFILE)
print config.sections()
print config.get('Credentials', 'accesskeyid')
  • 例如获取Credentials

    1
    2
    3
    config = ConfigParser.ConfigParser()
    config.read(CONFIGFILE)
    print config.sections()
  • 获取accesskeyid值

    1
    2
    3
    config = ConfigParser.ConfigParser()
    config.read(CONFIGFILE)
    print config.get('Credentials', 'accesskeyid')
  • 修改accesskeyid值

    1
    2
    3
    4
    5
    6
    config = ConfigParser.ConfigParser()
    config.read(CONFIGFILE)
    config.remove_option('Credentials', 'accesskeyid')
    config.set('Credentials', 'accesskeyid', 'test')
    with open(config_file, 'w+') as f:
    config.write(f)

模块官网地址: https://docs.python.org/2/library/configparser.html

Comments

2018-02-11