Skip to Content
Python 技術手冊 第三版
book

Python 技術手冊 第三版

by lex Martelli, Anna Martelli Ravenscroft, Steve Holden
January 2018
Intermediate to advanced content levelIntermediate to advanced
856 pages
17h 17m
Chinese
GoTop Information, Inc.
Content preview from Python 技術手冊 第三版
714
|
23 章 結構化文字:XML
從頭建置一個 ElementTree
有的時候,你的任務並非從一個現有的 XML 文件開始,取而代之,你得
從你的程式碼從不同來源,例如一個 CSV 文件或某種資料庫,得到的資料
製作出一個 XML 文件。
用於這種任務的程式碼類似我們剛才展示過的,用來編輯一個現有
ElementTree
的程式碼,只不過要新增一小段程式碼來建置一開始是空的一
棵樹。
舉例來說,假設你有一個 CSV 檔案,
menu.csv
,它的兩個以逗號分隔的欄
位是食物的卡路里和名稱,每個食物一列。你的任務是建置一個 XML
案,
menu.xml
,類似我們在前面範例中剖析的那個。這裡是那麼做的方式
之一:
import csv
from xml.etree import ElementTree as et
menu = et.Element('menu')
tree = et.ElementTree(menu)
with open('menu.csv') as f:
r = csv.reader(f)
for calories, namestr in r:
food = et.SubElement(menu, 'food')
cals = et.SubElement(food, 'calories')
cals.text = calories
name = et.SubElement(food, 'name')
name.text = namestr
tree.write('menu.xml') ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

測試驅動開發|使用 Python

測試驅動開發|使用 Python

Harry J.W. Percival
Linux 内核观测技术BPF

Linux 内核观测技术BPF

David Calavera, Lorenzo Fontana

Publisher Resources

ISBN: 9789864766819