PR

Pythonでzipファイルを解凍せずにzipファイル内の指定したファイルを読み込む

Python Python
Python

Pythonでzipファイルを解凍せずにzipファイル内の指定したファイルを読み込む方法について書きます。

zipファイル(sample.zip)内のxmlファイル(sample.xml)を読み込むサンプルプログラムです。
zipをディスク上に解凍せずに指定したファイルを読み込むことができるのでとても便利です。

sample.zip内のsample.xmlの例

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>

Pythonプログラムは下記の通りです。

import zipfile
import xml.etree.ElementTree as ET

with zipfile.ZipFile("sample.zip", "r") as result:
	root = ET.fromstring(result.read("sample.xml"))
	if root:
		print(root[0].get("name"))
		print(root[0].find("year").text)

実行結果

Liechtenstein
2008

以上!

タイトルとURLをコピーしました