使用ConfigParser模塊讀寫ini文件php
ConfigParserPython的ConfigParser Module中定義了3個類對INI文件進行操做。分別是RawConfigParser、ConfigParser、SafeConfigParser。模塊所解析的ini配置文件是由多個section構成,每一個section名用中括號‘[]’包含,每一個section下可有多個配置項相似於key-value形式,html
配置文件a.ini以下:python
# 註釋1 ; 註釋2 [section1] k1 = v1 k2:v2 user=egon age=18 is_admin=true salary=31
[section2] k1 = v1
讀取mysql
import configparser config=configparser.ConfigParser() config.read('a.ini') #查看全部的標題 res=config.sections() #['section1', 'section2'] print(res) #查看標題section1下全部key=value的key options=config.options('section1') print(options) #['k1', 'k2', 'user', 'age', 'is_admin', 'salary'] #查看標題section1下全部key=value的(key,value)格式 item_list=config.items('section1') print(item_list) #[('k1', 'v1'), ('k2', 'v2'), ('user', 'egon'), ('age', '18'), ('is_admin', 'true'), ('salary', '31')] #查看標題section1下user的值=>字符串格式 val=config.get('section1','user') print(val) #egon #查看標題section1下age的值=>整數格式 val1=config.getint('section1','age') print(val1) #18 #查看標題section1下is_admin的值=>布爾值格式 val2=config.getboolean('section1','is_admin') print(val2) #True #查看標題section1下salary的值=>浮點型格式 val3=config.getfloat('section1','salary') print(val3) #31.0
改寫sql
import configparser config=configparser.ConfigParser() config.read('a.cfg') #刪除整個標題section2 config.remove_section('section2') #刪除標題section1下的某個k1和k2 config.remove_option('section1','k1') config.remove_option('section1','k2') #判斷是否存在某個標題 print(config.has_section('section1')) #判斷標題section1下是否有user print(config.has_option('section1','')) #添加一個標題 config.add_section('egon') #在標題egon下添加name=egon,age=18的配置 config.set('egon','name','egon') config.set('egon','age',18) #報錯,必須是字符串 #最後將修改的內容寫入文件,完成最終的修改 config.write(open('a.cfg','w'))
好多軟件的常見文檔格式以下,文件名爲test.ini:cookie
[DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes [bitbucket.org] User = hg [topsecret.server.com] Port = 50022 ForwardX11 = no
php.ini文件的格式也是如此
[PHP] engine = On short_open_tag = Off asp_tags = Off precision = 14 output_buffering = 4096 zlib.output_compression = Off implicit_flush = Off unserialize_callback_func = serialize_precision = 17 disable_functions = disable_classes = zend.enable_gc = On expose_php = On max_execution_time = 30 max_input_time = 60 memory_limit = 128M error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT display_errors = Off display_startup_errors = Off log_errors = On log_errors_max_len = 1024 ignore_repeated_errors = Off ignore_repeated_source = Off report_memleaks = On track_errors = Off html_errors = On variables_order = "GPCS" request_order = "GP" register_argc_argv = Off auto_globals_jit = On post_max_size = 8M auto_prepend_file = auto_append_file = default_mimetype = "text/html" doc_root = user_dir = enable_dl = Off file_uploads = On upload_max_filesize = 2M max_file_uploads = 20 allow_url_fopen = On allow_url_include = Off default_socket_timeout = 60 [CLI Server] cli_server.color = On [Date] [filter] [iconv] [intl] [sqlite] [sqlite3] [Pcre] [Pdo] [Pdo_mysql] pdo_mysql.cache_size = 2000 pdo_mysql.default_socket= [Phar] [mail function] SMTP = localhost smtp_port = 25 sendmail_path = /usr/sbin/sendmail -t -i mail.add_x_header = On [SQL] sql.safe_mode = Off [ODBC] odbc.allow_persistent = On odbc.check_persistent = On odbc.max_persistent = -1 odbc.max_links = -1 odbc.defaultlrl = 4096 odbc.defaultbinmode = 1 [Interbase] ibase.allow_persistent = 1 ibase.max_persistent = -1 ibase.max_links = -1 ibase.timestampformat = "%Y-%m-%d %H:%M:%S" ibase.dateformat = "%Y-%m-%d" ibase.timeformat = "%H:%M:%S" [MySQL] mysql.allow_local_infile = On mysql.allow_persistent = On mysql.cache_size = 2000 mysql.max_persistent = -1 mysql.max_links = -1 mysql.default_port = mysql.default_socket = mysql.default_host = mysql.default_user = mysql.default_password = mysql.connect_timeout = 60 mysql.trace_mode = Off [MySQLi] mysqli.max_persistent = -1 mysqli.allow_persistent = On mysqli.max_links = -1 mysqli.cache_size = 2000 mysqli.default_port = 3306 mysqli.default_socket = mysqli.default_host = mysqli.default_user = mysqli.default_pw = mysqli.reconnect = Off [mysqlnd] mysqlnd.collect_statistics = On mysqlnd.collect_memory_statistics = Off [OCI8] [PostgreSQL] pgsql.allow_persistent = On pgsql.auto_reset_persistent = Off pgsql.max_persistent = -1 pgsql.max_links = -1 pgsql.ignore_notice = 0 pgsql.log_notice = 0 [Sybase-CT] sybct.allow_persistent = On sybct.max_persistent = -1 sybct.max_links = -1 sybct.min_server_severity = 10 sybct.min_client_severity = 10 [bcmath] bcmath.scale = 0 [browscap] [Session] session.save_handler = files session.use_cookies = 1 session.use_only_cookies = 1 session.name = PHPSESSID session.auto_start = 0 session.cookie_lifetime = 0 session.cookie_path = / session.cookie_domain = session.cookie_httponly = session.serialize_handler = php session.gc_probability = 1 session.gc_divisor = 1000 session.gc_maxlifetime = 1440 session.bug_compat_42 = Off session.bug_compat_warn = Off session.referer_check = session.cache_limiter = nocache session.cache_expire = 180 session.use_trans_sid = 0 session.hash_function = 0 session.hash_bits_per_character = 5 url_rewriter.tags = "a=href,area=href,frame=src,input=src,form=fakeentry" [MSSQL] mssql.allow_persistent = On mssql.max_persistent = -1 mssql.max_links = -1 mssql.min_error_severity = 10 mssql.min_message_severity = 10 mssql.compatability_mode = Off mssql.secure_connection = Off [Assertion] [mbstring] [gd] [exif] [Tidy] tidy.clean_output = Off [soap] soap.wsdl_cache_enabled=1 soap.wsdl_cache_dir="/tmp" soap.wsdl_cache_ttl=86400 soap.wsdl_cache_limit = 5 [sysvshm] [ldap] ldap.max_links = -1 [mcrypt] [dba]
1 獲取全部節點session
import configparser config=configparser.ConfigParser() config.read('test.ini',encoding='utf-8') res=config.sections() print(res) ''' 打印結果: ['bitbucket.org', 'topsecret.server.com'] '''
2 獲取指定節點下全部的鍵值對app
import configparser config=configparser.ConfigParser() config.read('test.ini',encoding='utf-8') res=config.items('bitbucket.org') print(res) ''' 打印結果:(包含DEFAULT以及bitbucket.org這倆標題下全部的items) [('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')] '''
3 獲取指定節點下全部的建dom
import configparser config=configparser.ConfigParser() config.read('test.ini',encoding='utf-8') res=config.options('bitbucket.org') print(res) ''' 打印結果:(包含DEFAULT以及bitbucket.org這倆標題下全部的鍵) ['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']'''
4 獲取指定節點下指定key的值socket
import configparser config=configparser.ConfigParser() config.read('test.ini',encoding='utf-8') res1=config.get('bitbucket.org','user') res2=config.getint('topsecret.server.com','port') res3=config.getfloat('topsecret.server.com','port') res4=config.getboolean('topsecret.server.com','ForwardX11') print(res1) print(res2) print(res3) print(res4) ''' 打印結果: hg 50022 50022.0 False '''
5 檢查、刪除、添加節點
import configparser config=configparser.ConfigParser() config.read('test.ini',encoding='utf-8') #檢查 has_sec=config.has_section('bitbucket.org') print(has_sec) #打印True #添加節點 config.add_section('egon') #已經存在則報錯 config['egon']['username']='gangdan' config['egon']['age']='18' config.write(open('test.ini','w')) #刪除節點 config.remove_section('egon') config.write(open('test.ini','w'))
6 檢查、刪除、設置指定組內的鍵值對
import configparser config=configparser.ConfigParser() config.read('test.ini',encoding='utf-8') #檢查 has_sec=config.has_option('bitbucket.org','user') #bitbucket.org下有一個鍵user print(has_sec) #打印True #刪除 config.remove_option('DEFAULT','forwardx11') config.write(open('test.ini','w')) #設置 config.set('bitbucket.org','user','gangdang') config.write(open('test.ini','w'))
import configparser config = configparser.ConfigParser() config["DEFAULT"] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9'} config['bitbucket.org'] = {} config['bitbucket.org']['User'] = 'hg' config['topsecret.server.com'] = {} topsecret = config['topsecret.server.com'] topsecret['Host Port'] = '50022' # mutates the parser topsecret['ForwardX11'] = 'no' # same here config['DEFAULT']['ForwardX11'] = 'yes' with open('example.ini', 'w') as configfile: config.write(configfile)