Python 3でYAMLファイルを解析する方法

PYTHON3 チュートリアル

PyYAMLの基本的な使い方

まず、PyYAMLを使用してYAMLファイルを読み込み、Pythonオブジェクトに変換する方法について説明します。以下の例では、YAMLファイルからデータを読み込み、それを表示します。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import yaml
# YAMLファイルを開いて読み込む
with open('example.yaml', 'r') as file:
data = yaml.safe_load(file)
print(data)
import yaml # YAMLファイルを開いて読み込む with open('example.yaml', 'r') as file: data = yaml.safe_load(file) print(data)
import yaml

# YAMLファイルを開いて読み込む
with open('example.yaml', 'r') as file:
    data = yaml.safe_load(file)

print(data)

PythonデータをYAML形式で保存する

次に、Pythonの辞書をYAMLファイルに書き出す方法を示します。以下のコードでは、Pythonの辞書を作成し、それをYAML形式でファイルに保存します。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import yaml
# Pythonの辞書
data = {
'name': 'Yamada',
'age': 30,
'skills': ['Python', 'YAML']
}
# 辞書をYAMLファイルに書き出す
with open('output.yaml', 'w') as file:
yaml.safe_dump(data, file)
import yaml # Pythonの辞書 data = { 'name': 'Yamada', 'age': 30, 'skills': ['Python', 'YAML'] } # 辞書をYAMLファイルに書き出す with open('output.yaml', 'w') as file: yaml.safe_dump(data, file)
import yaml

# Pythonの辞書
data = {
    'name': 'Yamada',
    'age': 30,
    'skills': ['Python', 'YAML']
}

# 辞書をYAMLファイルに書き出す
with open('output.yaml', 'w') as file:
    yaml.safe_dump(data, file)

YAMLファイルの詳細な読み込み

YAMLファイルが複雑な構造を持つ場合、それを適切に扱う方法が必要です。以下の例では、ネストされた構造を持つYAMLファイルを読み込み、特定のデータを抽出して表示します。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import yaml
# 複雑なYAMLファイルを開いて読み込む
with open('complex_example.yaml', 'r') as file:
data = yaml.safe_load(file)
# 特定のデータを抽出して表示
print(data['user']['name'])
print(data['user']['projects'][0]['name'])
import yaml # 複雑なYAMLファイルを開いて読み込む with open('complex_example.yaml', 'r') as file: data = yaml.safe_load(file) # 特定のデータを抽出して表示 print(data['user']['name']) print(data['user']['projects'][0]['name'])
import yaml

# 複雑なYAMLファイルを開いて読み込む
with open('complex_example.yaml', 'r') as file:
    data = yaml.safe_load(file)

# 特定のデータを抽出して表示
print(data['user']['name'])
print(data['user']['projects'][0]['name'])

これらのコードサンプルは、PyYAMLを使用してYAMLデータを扱う基本的な方法を示しています。YAMLファイルの読み込みから、Pythonデータ構造への変換、さらにはYAML形式でのデータ保存まで、幅広くカバーしています。

購読
通知


0 Comments
Inline Feedbacks
View all comments