天天看點

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
"""