最新消息:

Python课程系列:Python 如何读取 property file

Python 少儿编程 1551浏览 0评论

Python课程系列:Python 如何读取 property file

Java中会利用 .property 档案来存放一些系统变量,但在 Python 上并没有专门处理 properties 格式的档案,只有 ini 格式的档案,因此本文分享如何处理 Python 读取 ini 内的 properties

 

Python课程系列:Python 如何读取 property file

准备

1.本文是在 ubuntu 环境下执行Python2.7环境

2.程序编辑器

执行步骤

1. 安装 configparser 套件

于程序执行环境下 pip 安装指令

pip install configparser

2. 建立 ini 档案

新增一个 test.ini 档案,于档案内写入相关系统参数,本篇文章的范例主要是读取 DB 的联机信息

vi test.ini

[DEFAULT]

mssql_host = 140.92.27.37:1433

mssql_username =

mssql_password =

mssql_database =

3. 程序代码撰写

新增一只 Python 程序,于程序内 import 刚刚安装的 configparser lib,接着读取 test.ini 档案后,即可抓取 ini 档案的参数值

vi test.py

import pymssql

import os

import sys

import configparser

config = configparser.ConfigParser()

config.read(‘test.ini’)

host = config['DEFAULT']['mssql_host']

username = config['DEFAULT']['mssql_username']

password =config['DEFAULT']['mssql_password']

database =config['DEFAULT']['mssql_database']

conn = pymssql.connect(host, username, password,database, charset=”utf8″)

print(username)

4. 执行程序

python test.py

这样就可以读取 ini 内的 properties

您必须 登录 才能发表评论!