1
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?

ヘルスケアのxmlデータをcsvに変換するpython3スクリプト

Posted at

前書き

Python の標準ライブラリ に含まれている(xml.etree.ElementTree, csv, os) を使ってスプリクトを書いた方が簡単で、その後のデータの加工など使い勝手がいいことから、「ahcd-go」をやめて、pythonにしました。

環境

iMac Retina 5k, 27-inch, 2017
macOS Ventura 13.7.4
MacBook Air (15インチ, M2, 2023)
MacOS:Sonoma14.5

実行結果

main.pyを実行
05.png

exportDataディレクトリに、変換後のcsvができる
06.png
あとは、通常の方法でdataframeなどで、加工する

python3スクリプト

import os
import csv
import xml.etree.ElementTree as ET

# -----------------------------------------------------
xml_file = "export.xml"  # XMLファイルのパス
output_dir = "exportData"  # CSV出力フォルダ

# 必要なデータのマッピング
FILE_NAME_MAPPING = {
    "HKQuantityTypeIdentifierActiveEnergyBurned",
    "HKQuantityTypeIdentifierBasalEnergyBurned",
    "HKQuantityTypeIdentifierBodyFatPercentage",
    "HKQuantityTypeIdentifierBodyMass",
    "HKQuantityTypeIdentifierStepCount",
    "HKQuantityTypeIdentifierWalkingSpeed",
    "HKQuantityTypeIdentifierWalkingStepLength",
    "HKQuantityTypeIdentifierDistanceWalkingRunning"
}

# XML を解析
tree = ET.parse(xml_file)
root = tree.getroot()

# 出力フォルダの作成
os.makedirs(output_dir, exist_ok=True)

# 各データを適切なCSVに保存
for record in root.findall("Record"):
    record_type = record.get("type")
    if record_type not in FILE_NAME_MAPPING:
        continue  # 不要なデータはスキップ
    
    file_name = f"{record_type}.csv"
    file_path = os.path.join(output_dir, file_name)
    
    # 新規作成時にヘッダーを追加
    write_header = not os.path.exists(file_path) or os.stat(file_path).st_size == 0
    
    with open(file_path, mode="a", newline="", encoding="utf-8") as file:
        writer = csv.writer(file)
        if write_header:
            writer.writerow(["作成日", "Value", "StartDate", "EndDate"])
        
        # 取得するデータを書き込む
        writer.writerow([
            record.get("creationDate", ""),
            record.get("value", ""),
            record.get("startDate", ""),
            record.get("endDate", "")
        ])

print("XMLからCSVへの変換が完了しました。")

<ご参考>iPhoneからヘルスケアの”xmlデータ”の取得方法

・「ヘルスケア」アプリを開きます。
・右上にある写真またはイニシャルをタップします。
・「すべてのヘルスケアデータを書き出す」をタップします。
01.png

・「書き出す」をクリック
・「書き出したデータ」で好きなところにダウンロードする
02.png
・例:「ファイルに保存」からPCのFinderにダウンロード
(事前に保存するディレクトリを作っておくか決めておく)
03.png

スクリーンショット 2025-03-10 10.51.28.png

以上です。

1
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
1
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?