Python:【gzipファイルを開いて1行ずつ処理】実行例


逆引きキーワード

  • shell
    • サンプルgzipファイル作成
  • ipython
    • gzipファイルを開いてbyte型を確認
    • byte型を文字列に変換して表示

前提

  • 特になし

実行ログ

準備

gzipファイル作成

cat <<+ > testfile
welcome!
broaden your horizons by futa.
+
gzip -c testfile > testfile.gz
ls -l testfile.gz
ipython
-rw-rw-r-- 1 futa futa 69 Mar  7 17:26 testfile.gz
Python 3.9.5 (default, Jun  4 2021, 12:28:51)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.31.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]:
  • プロンプトがIPthonに切り替わる
    (以降、IPthonのプロンプトは省略)

実行

gzipファイル開く

import gzip
with gzip.open('./testfile.gz') as f:
    file = f.read()
print(file)
print(type(file))
b'welcome!\nbroaden your horizons by futa.\n'
<class 'bytes'>
  • 文字列はbyte型で保存されている
    • 文字列"の前に「b」

byte型を文字列に変換してから表示

for line in file.decode().split('\n'):
    print(line)
welcome!
broaden your horizons by futa.
  • 文字列の区切りとして改行コード「\n」を指定


Posted by futa