Skip to content

Instantly share code, notes, and snippets.

@moosetraveller
Created August 25, 2022 17:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moosetraveller/00d48c25cfb86683b86aa9a4fe571848 to your computer and use it in GitHub Desktop.
Save moosetraveller/00d48c25cfb86683b86aa9a4fe571848 to your computer and use it in GitHub Desktop.
How to open file from URL with Python

How to open a file from URL with Python

Using urllib.request

# !pip install cairosvg matplotlib pillow

import io
from urllib.request import Request, urlopen
import xml.etree.ElementTree as ET

import cairosvg
import matplotlib.pyplot as plt
from PIL import Image


SVG_URL = "https://upload.wikimedia.org/wikipedia/commons/8/8b/" \
          "Kantone_der_Schweiz.svg"

request = Request(SVG_URL)

with urlopen(request) as response:

    # read and parse SVG file from URL
    svg = ET.parse(io.BytesIO(response.read()))

    canton_zurich = svg.find(".//*[@id='path2536']")

    canton_zurich.set("style", "fill:#12e9a1")

    # get SVG as a string
    svg_string = ET.tostring(svg.getroot())

    # plot with matplotlib
    # see also https://stackoverflow.com/a/70007704/42659
    png = cairosvg.svg2png(svg_string)
    image = Image.open(io.BytesIO(png))
    plt.imshow(image)

Using fsspec

# !pip install cairosvg matplotlib pillow fsspec

import io
from urllib.request import Request, urlopen
import xml.etree.ElementTree as ET

import fsspec

import cairosvg
import matplotlib.pyplot as plt
from PIL import Image


SVG_URL = "https://upload.wikimedia.org/wikipedia/commons/8/8b/" \
          "Kantone_der_Schweiz.svg"

with fsspec.open(SVG_URL) as file:

    # read and parse SVG file from URL
    svg = ET.parse(file)

    canton_zurich = svg.find(".//*[@id='path2536']")

    canton_zurich.set("style", "fill:#12e9a1")

    # get SVG as a string
    svg_string = ET.tostring(svg.getroot())

    # plot with matplotlib
    # see also https://stackoverflow.com/a/70007704/42659
    png = cairosvg.svg2png(svg_string)
    image = Image.open(io.BytesIO(png))
    plt.imshow(image)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment