Python Glossary Русский

all Python 3urllib.requestterm

urllib.request.FileHandler

protocol handlers

The handler for file:// URLs: it reads a local file and returns content type, size and modification date headers.

Syntax

urllib.request.FileHandler()

Only a local host is allowed in the address: 'file://server/x' raises URLError. There is no relative file:// URL, and spaces and non-ASCII letters must be encoded, so build the URL from a path with Path.resolve().as_uri() — as_uri() itself raises ValueError on a relative path. The response has no HTTP code: resp.status is None.

Examples

import pathlib, urllib.request
path = pathlib.Path('notes.txt')
path.write_text('abc', encoding='utf-8')
with urllib.request.urlopen(path.resolve().as_uri()) as resp:
    print(resp.headers['Content-type'], resp.headers['Content-length'], resp.status)
# → text/plain 3 None
import urllib.error, urllib.request
try:
    urllib.request.urlopen('file://server/share/x.txt')
except urllib.error.URLError as e:
    print(type(e).__name__)  # → URLError

See also

Open in the full glossarydocs.python.orgReport an inaccuracy