天天看点

Python 配置文件与格式化输出

文章目录

  • ​​一、configparser模块​​
  • ​​二、格式化输出​​

在构建工程时,需要用到配置文件,用来配置项目的一些信息,比如数据库,请求网址,文件夹,线程、进程数等信息,这样就可以方便我们通过修改配置文件中的参数来很好地完成整个项目的功能修改或开发。配置文件一般区别于Python代码,会单独存放在一个文件夹中,方便管理,常见的配置文件格式有.conf, .ini, .yaml等。

下面接受几种常用的配置文件模块

一、configparser模块

使用configparser模块来处理conf、ini配置文件。

安装命令:​​

​pip install configparser​

一个为​

​mysql.conf​

​​,是MySQL的连接配置;另一个是Python代码,用于读取某张表的具体内容。

[mysql]
db_host=localhost
db_port=3306
db_user=root
db_password=
db_database=school      

读取测试:

from configparser import ConfigParser 
import pymysql 


config = ConfigParser() 
config.read("mysql.conf")


host = config.get("mysql","db_host")
port = config.get("mysql","db_port")
user = config.get("mysql","db_user")
password = config.get("mysql","db_password")
database = config.get("mysql","db_database")
print("host",type(host),host)
print("port",type(port),port)


db = pymysql.connect(host=host,port=port,user=user,password=password,database=database)
cursor = db.cursor()
cursor.execute("select * from datebase_name")
for row in cursor.fetchall():
  print(row)

cursor.close()
db.close()      

更多详情:https://www.jianshu.com/p/aadd86f8d38e

二、格式化输出

python console下想实现类excel 一样的格式化表格输出 ,可以通过以下三个模块实现 test_table、PrettyTable、texttable

关于更多请查看:https://pypi.org/project/texttable/

安装方法:​​

​pip install -i https://pypi.tuna.tsinghua.edu.cn/simple texttable​

python打印表格式数据-星号或注释

def printPicnic(itemsDict,leftWidth,rightWidth):
    print('PICNIC ITEMS'.center(leftWidth + rightWidth,'-'))
    for k,v in itemsDict.items():
        print(k.ljust(leftWidth,'.')+str(v).rjust(rightWidth))

picnicItems = {'sandwitches':4,'apple':12,'cups':4,'cookies':8000}
printPicnic(picnicItems,12,5)
printPicnic(picnicItems,20,6)

"""
>>> printPicnic(picnicItems,12,5)
---PICNIC ITEMS--
sandwitches.    4
apple.......   12
cups........    4
cookies..... 8000
>>> printPicnic(picnicItems,20,6)
-------PICNIC ITEMS-------
sandwitches.........     4
apple...............    12
cups................     4
cookies.............  8000
"""      
from prettytable import PrettyTable

x = PrettyTable(["Hero name", "player", "sorce", "Annual Rainfall"])
x.align["Hero name"] = "l"  # Left align Hero name
x.padding_width = 1         # One space between column edges and contents (default)
x.add_row(["达摩","张三", 1158259, 600.5])
x.add_row(["典韦","李四", 1857594, 1146.4])
x.add_row(["曹操", "王五", 120900, 1714.7])
x.add_row(["钟无艳", "赵六", 205556, 619.5])
x.add_row(["墨子", "王麻子", 4336374, 1214.8])
x.add_row(["赵云", "二愣子", 3806092, 646.9])
x.add_row(["吕布", "狗子", 1554769, 869.4])
print(x) 


"""
+-----------+--------+---------+-----------------+
| Hero name | player |  sorce  | Annual Rainfall |
+-----------+--------+---------+-----------------+
|    达摩   |  张三  | 1158259  |      600.5      |
|    典韦   |  李四  | 1857594  |      1146.4     |
|    曹操   |  王五  |  120900  |      1714.7     |
|   钟无艳  |  赵六  |  205556  |      619.5      |
|    墨子   | 王麻子 | 4336374  |      1214.8     |
|    赵云   | 二愣子 | 3806092  |      646.9      |
|    吕布   |  狗子  | 1554769  |      869.4      |
+-----------+--------+---------+-----------------+
"""      
from texttable import Texttable

table = Texttable()
table.set_cols_align(["l", "r", "c"])
table.set_cols_valign(["t", "m", "b"])
table.add_rows([["Name", "Age", "Nickname"],
                ["Mr\nXavier\nHuon", 32, "Xav'"],
                ["Mr\nBaptiste\nClement", 1, "Baby"]])
print(table.draw() + "\n")
"""
+----------+-----+----------+
|   Name   | Age | Nickname |
+==========+=====+==========+
| Mr       |     |          |
| Xavier   |  32 |          |
| Huon     |     |   Xav'   |
+----------+-----+----------+
| Mr       |     |          |
| Baptiste |   1 |          |
| Clement  |     |   Baby   |
+----------+-----+----------+
"""

table = Texttable()
table.set_deco(Texttable.HEADER)
table.set_cols_dtype(['t',  # text
                      'f',  # float (decimal)
                      'e',  # float (exponent)
                      'i',  # integer
                      'a']) # automatic
table.set_cols_align(["l", "r", "r", "r", "l"])
table.add_rows([["text",    "float", "exp", "int", "auto"],
                ["abcd",    "67",    654,   89,    128.001],
                ["efghijk", 67.5434, .654,  89.6,  12800000000000000000000.00023],
                ["lmn",     5e-78,   5e-78, 89.4,  .000000000000128],
                ["opqrstu", .023,    5e+78, 92.,   12800000000000000000000]])
print(table.draw())

"""
 text     float       exp      int     auto
==============================================
abcd      67.000   6.540e+02    89   128.001
efghijk   67.543   6.540e-01    90   1.280e+22
lmn        0.000   5.000e-78    89   0.000
opqrstu    0.023   5.000e+78    92   1.280e+22
"""