0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python】表をいい感じにprintしたい!

Posted at

はじめに

 sqlite3を使って、PythonでRDBを作成できますが、「可視化ってほどじゃないけど、ちょっと中身確認したいな〜」ってことありませんか?そんな時に便利なモジュールを見つけたので、使い方と合わせてご紹介します。

tabulate

pip install tabulate

まずはモジュールをpipします。あとは、以下のサンプルのように使うことができます

from tabulate import tabulate

header_names  = ['id', 'name', 'age']
values = [
    ['001', 'taro', '17'],
    ['002', 'hanako', '14'],
    ['003', 'takashi', '35']
]
print(tabulate(values, headers=header_names, tablefmt="pretty"))
出力
+-----+---------+-----+
| id  |  name   | age |
+-----+---------+-----+
| 001 |  taro   | 17  |
| 002 | hanako  | 14  |
| 003 | takashi | 35  |
+-----+---------+-----+

 tablefmtという引数は、表の形を指定できるものです。一行ごとに区切りが入るものなど、他にもいくつかありますが、prettyというのを例に使ってみました。指定しないデフォルトの物は以下の見た目です。

出力
  id  name       age
----  -------  -----
 001  taro        17
 002  hanako      14
 003  takashi     35

tabulateに関しては、以下の記事に詳しくまとまっていました。より詳細な情報が知りたい方はご覧ください。(今回はちょっと中身を見たいだけなので割愛)

sqlite3との併用

 テーブルの内容のほかに、ヘッダーを取得するので、以下のように関数を定義しておくと使い勝手が良いです。

import sqlite3
from tabulate import tabulate

dbname = 'sample.db'
conn = sqlite3.connect(dbname)
cur = conn.cursor()
cur.execute(
    '''
    CREATE TABLE IF NOT EXISTS people(
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name STRING,
        age INTEGER);
    '''
)
cur.execute(
    '''
    INSERT INTO people(name, age) 
    VALUES
        ('taro', '17'),
        ('hanako', '14'),
        ('takashi', 35);
    '''
)

#こんな風に関数を定義
def print_table(table_name):
    # テーブルのカラム名を取得
    cur.execute(f"PRAGMA table_info({table_name});")
    columns = cur.fetchall()
    # カラム名だけを抽出して表示
    field_names = [column[1] for column in columns]
    cur.execute(f'SELECT * FROM {table_name};')
    print(tabulate(cur.fetchall(), headers=field_names, tablefmt="pretty"))

print_table('people')
cur.close()
conn.close()

まとめ

 ちょっとしたデータベースの可視化には、tabulateを使うと便利!

最後に

 ここまで読んで下さりありがとうございました。本気で可視化しながらデータベースを作りたい人は、openpyxlとかを使ってExcelに出力する方が良いですが、ちょっとした出力には、こちらの方が便利だと思います。pprintも試してみましたが、ちょっと見づらいので、いままでpprintでやっていた人には、乗り換えることをお勧めします。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?