LoginSignup
0
0

More than 5 years have passed since last update.

Windows 10 Pro x64 + Python3 で Jsonファイルの読み書きを試してみる

Last updated at Posted at 2019-02-11

目的

参考サイトでjsonデータを取得後、ファイルに書きこんだ後、読み込んでみる
※まずは基本的な読み書きを確認
※自分用の確認メモ

サンプルコード

PS > python -V
Python 3.7.2
組み込み関数:openで指定可能なモード
'r':読み込み用に開く (デフォルト)
'w':書き込み用に開き、まずファイルを切り詰める(上書?)
'x':排他的な生成に開き、ファイルが存在する場合は失敗する
'a':書き込み用に開き、ファイルが存在する場合は末尾に追記する
'b':バイナリモード
't':テキストモード (デフォルト)
'+':ディスクファイルを更新用に開く (読み込み/書き込み)

# Windows Add env PYTHONIOENCODING = UTF-8 & restart vscode

import http.client
import json

# 表示するユーザ名
USER_ID = "tabizou"
# ユーザの投稿数
ITEM_NUM = 10
# ページ番号 (1から100まで)
PAGE = "1"
# 1ページあたりに含まれる要素数 (1から100まで)
PAR_PAGE = "100"

conn = http.client.HTTPSConnection("qiita.com", 443)
conn.request("GET", "/api/v2/users/" + USER_ID + "/items?page=" + PAGE + "&per_page=" + PAR_PAGE)
res = conn.getresponse()
print(res.status, res.reason)

data = res.read().decode("utf-8")
#----------追加---------------------------------------
print(type(data))

# json ファイルの書き込み
with open('qiita.json', 'w', encoding='UTF-8') as f:
    for chunk in data:
        f.write(chunk)
    print("書き込み終了")

conn.close()

# json ファイルの読み込み
with open('qiita.json', 'r', encoding='UTF-8') as f:
    jsonstr = json.load(f)

print(type(jsonstr))
#----------追加---------------------------------------
print("==========================================================")
# ヘッダ出力
print("\"no\",\"created_at\",\"tile\",\"url\"")

# 投稿数を指定
for num in range(ITEM_NUM):
    created_at = jsonstr[num]['created_at']
    tile = jsonstr[num]['title']
    url = jsonstr[num]['url']

    # ダブルクォートありCSV形式で出力
    print("\"" + str(num) + "\",\"" + created_at + "\",\"" + tile + "\",\"" + url + "\"")

print("==========================================================")

参考にしたのは以下のサイト

Qiita API v2 を使って投稿一覧を取得する
json --- JSON エンコーダおよびデコーダ
7. 入力と出力
組込関数:open

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