Docs

Using MarkItDown in Python

Updated 2026-11-15·Upstream source ↗
Markdown view

One class, six conversion methods, one result object and a small family of exceptions. Every example on this page was executed on version 0.1.9, and the output shown is the output we captured.

Short answer

Import the class, build it once, convert a path, and read .markdown:

Pythonapi-convert-path.py
from markitdown import MarkItDown

md = MarkItDown()
result = md.convert("samples/report.docx")
print(type(result).__name__)
print(result.markdown[:160])
Output · markitdown 0.1.9 · Python 3.13.18 · 2026-11-15
DocumentConverterResult
Pilot Report: Field Station Alpha

# 1. Summary

This report covers **three sites** during *spring 2026* <u>with underlined</u> ~~and struck text.~~

## 1.1 Key

captured result

Install the extras for your file types first (extras); the check script and the tables on the missing-dependency page show what is installed.

Tested with markitdown 0.1.9 · Python 3.13 · markitdown[all] 0.1.9 · every snippet executed by scripts/run_snippets.py (Linux lab); thread test and conversions also run in CI on three systems · 2026-11-15 · evidence: api-surface.json

Choose the right method for your input

You haveCallNote
A local file path you controlconvert_local (or convert)str and pathlib.Path both work
Bytes, an open binary file, an uploadconvert_stream with StreamInfo hintsthe stream must be binary
A requests response you fetchedconvert_responseits headers give the type and charset
A URLconvert_uri (alias convert_url)fetched with the instance's session
A file: or data: URIconvert_uri
A string of HTML or textwrap it as a bytes stream with a type hintbelow
Not sureconvertaccepts all of the above
convert(x)convert_uriconvert_localconvert_responseconvert_stream
How convert routes its input. convert looks at the type of its argument: a string that starts with http or https, file or data goes to convert_uri; any other string or a Path goes to convert_local; a requests Response goes to convert_response; a binary file object goes to convert_stream. All four end in the same detection and converter selection.

Files on disk

convert takes a str or a pathlib.Path. A missing file raises FileNotFoundError and a folder raises IsADirectoryError:

Pythonapi-convert-pathlib.py
from pathlib import Path
from markitdown import MarkItDown

result = MarkItDown().convert(Path("samples") / "data.csv")
print(result.markdown)
Output · markitdown 0.1.9 · Python 3.13.18 · 2026-11-15
| station | rainfall_mm | notes |
| --- | --- | --- |
| Alpha | 412.5 | Battery, low |
| Bravo | 388.0 | OK \| stable |
| Charlie | 451.3 | café |

captured result

Pythonapi-local-path-errors.py
from markitdown import MarkItDown

md = MarkItDown()
for path in ("samples/missing.docx", "samples"):
    try:
        md.convert(path)
    except Exception as e:
        print(f"{path!r}: {type(e).__name__}")
Output · markitdown 0.1.9 · Python 3.13.18 · 2026-11-15
'samples/missing.docx': FileNotFoundError
'samples': IsADirectoryError

captured result

When the extension is wrong, tell MarkItDown with a hint (below). Write the result with an explicit encoding, because the default differs by system (why):

Pythonapi-write-utf8.py
from pathlib import Path
from markitdown import MarkItDown

text = MarkItDown().convert("samples/report.docx").markdown
Path("report.md").write_text(text, encoding="utf-8")   # explicit encoding: the same bytes on every system

data = Path("report.md").read_bytes()
print("bytes written:", len(data))
print("starts with a byte-order mark:", data[:3] == b"\xef\xbb\xbf")
print("keeps café, 東京 and the emoji:", all(s in data.decode("utf-8") for s in ("café", "東京", "\U0001F642")))
print("line endings: CRLF" if b"\r\n" in data else "line endings: LF")
Output · markitdown 0.1.9 · Python 3.13.18 · 2026-11-15
bytes written: 850
starts with a byte-order mark: False
keeps café, 東京 and the emoji: True
line endings: LF

captured result

Bytes, uploads and in-memory data

From bytes

Pythonapi-stream-bytesio.py
import io
from markitdown import MarkItDown

data = open("samples/report.docx", "rb").read()
result = MarkItDown().convert_stream(io.BytesIO(data))
print(result.markdown.splitlines()[0])
Output · markitdown 0.1.9 · Python 3.13.18 · 2026-11-15
Pilot Report: Field Station Alpha

captured result

Without hints MarkItDown detected the type from the bytes. When it cannot, say what you have; the fields of StreamInfo are:

Pythonapi-stream-info-fields.py
import dataclasses
from markitdown import StreamInfo

print([f.name for f in dataclasses.fields(StreamInfo)])
info = StreamInfo(extension=".pdf")
print(info.copy_and_update(mimetype="application/pdf", filename="a.pdf"))
print("frozen:", dataclasses.is_dataclass(info))
try:
    info.extension = ".docx"
except dataclasses.FrozenInstanceError as e:
    print("FrozenInstanceError:", e)
Output · markitdown 0.1.9 · Python 3.13.18 · 2026-11-15
['mimetype', 'extension', 'charset', 'filename', 'local_path', 'url']
StreamInfo(mimetype='application/pdf', extension='.pdf', charset=None, filename='a.pdf', local_path=None, url=None)
frozen: True
FrozenInstanceError: cannot assign to field 'extension'

captured result

A charset hint fixes a mis-detected text encoding:

Pythonapi-stream-info-charset.py
from markitdown import MarkItDown, StreamInfo

md = MarkItDown()
raw = open("samples/data-cp1252.csv", "rb")
guess = md.convert_stream(raw)
print("no hint:\n" + guess.markdown)
raw.seek(0)
fixed = md.convert_stream(raw, stream_info=StreamInfo(extension=".csv", charset="cp1252"))
print("charset=cp1252:\n" + fixed.markdown)
Output · markitdown 0.1.9 · Python 3.13.18 · 2026-11-15
no hint:
| station | notes |
| --- | --- |
| Alpha | cafķ dķjÓ vu |
| Bravo | na’ve Ć5 |
charset=cp1252:
| station | notes |
| --- | --- |
| Alpha | café déjà vu |
| Bravo | naïve €5 |

captured result

From a web upload

Read the uploaded file into a binary buffer (io.BytesIO), pass the original file name and content type as hints, set a size limit before reading, and call convert_stream. A complete service is a separate recipe (web service).

Text-mode streams fail

A file opened in text mode is rejected with a TypeError: open it with "rb".

Pythonapi-text-stream-error.py
from markitdown import MarkItDown

with open("samples/data.csv", "r", encoding="utf-8") as f:   # text mode, not "rb"
    try:
        MarkItDown().convert(f)
    except TypeError as e:
        print("TypeError:", e)
Output · markitdown 0.1.9 · Python 3.13.18 · 2026-11-15
TypeError: Invalid source type: <class '_io.TextIOWrapper'>. Expected str, requests.Response, BinaryIO.

captured result

A stream that cannot seek is buffered in memory first:

Pythonapi-stream-nonseekable.py
import io
from markitdown import MarkItDown

class OneWay(io.RawIOBase):
    """A binary stream that reads forward only, like a pipe or a socket."""
    def __init__(self, data): self._b = io.BytesIO(data)
    def readable(self): return True
    def seekable(self): return False
    def readinto(self, buf): return self._b.readinto(buf)

stream = OneWay(open("samples/report.docx", "rb").read())
print("seekable:", stream.seekable())
result = MarkItDown().convert_stream(stream)
print(result.markdown.splitlines()[0])
Output · markitdown 0.1.9 · Python 3.13.18 · 2026-11-15
seekable: False
Pilot Report: Field Station Alpha

captured result

Converting a string

Pythonapi-convert-string.py
import io
from markitdown import MarkItDown, StreamInfo

md = MarkItDown()
html = "<h1>Notes</h1><p>Hello <b>world</b> and <a href='https://example.org'>a link</a>.</p><ul><li>one</li><li>two</li></ul>"

# a string is not a path: wrap it as bytes and say what it is
result = md.convert_stream(io.BytesIO(html.encode("utf-8")), stream_info=StreamInfo(extension=".html", charset="utf-8"))
print(result.markdown)

# plain text passes through unchanged
text = md.convert_stream(io.BytesIO("just some text\nsecond line".encode()), stream_info=StreamInfo(extension=".txt"))
print(repr(text.markdown))
Output · markitdown 0.1.9 · Python 3.13.18 · 2026-11-15
# Notes

Hello **world** and [a link](https://example.org).

* one
* two
'just some text\nsecond line'

captured result

URLs

convert fetches http(s) URLs with the instance's requests session. The default headers ask for Markdown first:

Pythonapi-default-headers.py
from markitdown import MarkItDown

result = MarkItDown().convert("http://127.0.0.1:8765/echo-headers")
print(result.markdown)
Output · markitdown 0.1.9 · Python 3.13.18 · 2026-11-15
{"Host": "127.0.0.1:8765", "User-Agent": "python-requests/2.34.2", "Accept-Encoding": "gzip, deflate", "Accept": "text/markdown, text/html;q=0.9, text/plain;q=0.8, */*;q=0.1", "Connection": "keep-alive"}

captured result

Pass your own session for headers, timeouts or a proxy:

Pythonapi-custom-session.py
import requests
from markitdown import MarkItDown

session = requests.Session()
session.headers.update({"User-Agent": "my-pipeline/1.0"})
result = MarkItDown(requests_session=session).convert("http://127.0.0.1:8765/echo-headers")
print(result.markdown)
Output · markitdown 0.1.9 · Python 3.13.18 · 2026-11-15
{"Host": "127.0.0.1:8765", "User-Agent": "my-pipeline/1.0", "Accept-Encoding": "gzip, deflate", "Accept": "*/*", "Connection": "keep-alive"}

captured result · The server echoes the request headers so you can see exactly what the library sent.

file: and data: URIs and requests responses work too:

Pythonapi-convert-uri.py
import base64, pathlib
from markitdown import MarkItDown

md = MarkItDown()
print(md.convert_uri(pathlib.Path("samples/data.csv").resolve().as_uri()).markdown.splitlines()[0])
payload = base64.b64encode(b"# Hello\n\nFrom a data URI.").decode()
print(md.convert_uri("data:text/markdown;base64," + payload).markdown)
Output · markitdown 0.1.9 · Python 3.13.18 · 2026-11-15
| station | rainfall_mm | notes |
# Hello

From a data URI.

captured result

Pythonapi-convert-response.py
import requests
from markitdown import MarkItDown

response = requests.get("http://127.0.0.1:8765/data.csv")
print("status:", response.status_code, "| content type:", response.headers.get("Content-Type"))
result = MarkItDown().convert_response(response)
print(result.markdown)
Output · markitdown 0.1.9 · Python 3.13.18 · 2026-11-15
status: 200 | content type: text/csv
| station | rainfall_mm | notes |
| --- | --- | --- |
| Alpha | 412.5 | Battery, low |
| Bravo | 388.0 | OK \| stable |
| Charlie | 451.3 | café |

captured result

Some sites answer 403 to scripts (web pages).

The result

Pythonapi-result-object.py
from markitdown import MarkItDown

result = MarkItDown().convert("samples/report.docx")
print("title:", result.title)
print("markdown is a str:", isinstance(result.markdown, str))
print("text_content is the same text:", result.text_content == result.markdown)
print("str(result) is the same text:", str(result) == result.markdown)
print("attributes:", sorted(a for a in vars(result)))
Output · markitdown 0.1.9 · Python 3.13.18 · 2026-11-15
title: None
markdown is a str: True
text_content is the same text: True
str(result) is the same text: True
attributes: ['markdown', 'title']

captured result

.markdown is the text; text_content is a deprecated alias and str(result) gives the same text. .title was None for our Word file: it is only set by some formats.

Handling errors

The exceptions form a small tree:

Pythonapi-hierarchy.py
import markitdown as m

for name in ("MarkItDownException", "MissingDependencyException", "UnsupportedFormatException", "FileConversionException"):
    cls = getattr(m, name)
    print(f"{name:28} bases: {[b.__name__ for b in cls.__bases__]}")
print("FailedConversionAttempt is an exception:", issubclass(m.FailedConversionAttempt, BaseException))
Output · markitdown 0.1.9 · Python 3.13.18 · 2026-11-15
MarkItDownException          bases: ['Exception']
MissingDependencyException   bases: ['MarkItDownException']
UnsupportedFormatException   bases: ['MarkItDownException']
FileConversionException      bases: ['MarkItDownException']
FailedConversionAttempt is an exception: False

captured result

Catch them in this order: a missing dependency (tell the user which extra), then an unsupported format, then a failed conversion, where attempts holds the real cause:

Pythonapi-exceptions-missing-extra.py
from markitdown import MarkItDown, FileConversionException, MissingDependencyException

try:
    MarkItDown().convert("samples/pdf-text.pdf")
except FileConversionException as e:
    inner = e.attempts[0].exc_info[1]
    print("outer:", type(e).__name__)
    print("inner:", type(inner).__name__, "| is MissingDependencyException:", isinstance(inner, MissingDependencyException))
    print(str(inner)[:240])
Output · markitdown 0.1.9 · Python 3.13.18 · 2026-11-15
outer: FileConversionException
inner: MissingDependencyException | is MissingDependencyException: True
PdfConverter recognized the input as a potential .pdf file, but the dependencies needed to read .pdf files have not been installed. To resolve this error, include the optional dependency [pdf] or [all] when installing MarkItDown. For exampl

captured result

Pythonapi-exceptions-unsupported.py
from markitdown import MarkItDown, UnsupportedFormatException

try:
    MarkItDown().convert("samples/unsupported.gif")
except UnsupportedFormatException as e:
    print(type(e).__name__)
    print(str(e)[:200])
Output · markitdown 0.1.9 · Python 3.13.18 · 2026-11-15
UnsupportedFormatException
Could not convert stream to Markdown. No converter attempted a conversion, suggesting that the filetype is simply not supported.

captured result

Pythonapi-exceptions-failed.py
from markitdown import MarkItDown, FileConversionException

try:
    MarkItDown().convert("samples/pdf-encrypted.pdf")
except FileConversionException as e:
    print("message line:", str(e).splitlines()[0])
    for attempt in e.attempts:
        print("converter:", type(attempt.converter).__name__, "| exception:", attempt.exc_info[0].__name__)
Output · markitdown 0.1.9 · Python 3.13.18 · 2026-11-15
message line: File conversion failed after 1 attempts:
converter: PdfConverter | exception: PDFPasswordIncorrect

captured result

A failed conversion does not break the instance: the next call works.

Pythonapi-error-after-error.py
from markitdown import MarkItDown

md = MarkItDown()
try:
    md.convert("samples/unsupported.gif")
except Exception as e:
    print("first call failed:", type(e).__name__)
print("second call works:", md.convert("samples/data.csv").markdown.splitlines()[0])
Output · markitdown 0.1.9 · Python 3.13.18 · 2026-11-15
first call failed: UnsupportedFormatException
second call works: | station | rainfall_mm | notes |

captured result

The meaning of each message is on the missing-dependency page; scanned PDFs raise no exception at all (they convert to nothing).

Configuring the converter

SettingWherePage
PluginsMarkItDown(enable_plugins=True)plugins
LLM client, model, promptconstructorimage descriptions
ExifTool pathexiftool_path=below
Word style mapconstructor, style_map=Word
Azure servicesconstructornot tested by us
HTTP sessionrequests_session=URLs
Keep image dataper call, keep_data_uris=Truebelow
Language, YouTube languagesper callaudio
Pythonapi-keep-data-uris.py
from markitdown import MarkItDown

md = MarkItDown()
short = md.convert("samples/docx-images-no-alt.docx").markdown
full = md.convert("samples/docx-images-no-alt.docx", keep_data_uris=True).markdown
print(len(short), "characters by default")
print(len(full), "characters with keep_data_uris=True")
print(short.splitlines()[2])
print(full.splitlines()[2][:60] + "...")
Output · markitdown 0.1.9 · Python 3.13.18 · 2026-11-15
103 characters by default
34507 characters with keep_data_uris=True
![](data:image/png;base64...)
![](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAoAAAAFoCA...

captured result

Pythonapi-exiftool-path.py
from markitdown import MarkItDown

try:
    MarkItDown(exiftool_path="/definitely/not/here/exiftool").convert("samples/photo-exif.jpg")
except Exception as e:
    print(type(e).__name__)
    print([str(a.exc_info[1])[:90] for a in getattr(e, "attempts", [])])
Output · markitdown 0.1.9 · Python 3.13.18 · 2026-11-15
FileConversionException
['Failed to invoke exiftool at /definitely/not/here/exiftool: [Errno 2] No such file or dire']

captured result · A wrong ExifTool path is an error, not a silent skip.

Pythonapi-style-map.py
from markitdown import MarkItDown

plain = MarkItDown().convert("samples/report.docx").markdown.splitlines()[0]
mapped = MarkItDown(style_map="p[style-name='Title'] => h1:fresh").convert("samples/report.docx").markdown.splitlines()[0]
print("default:   ", repr(plain))
print("style_map: ", repr(mapped))
Output · markitdown 0.1.9 · Python 3.13.18 · 2026-11-15
default:    'Pilot Report: Field Station Alpha'
style_map:  '# Pilot Report: Field Station Alpha'

captured result

Pythonapi-plugins.py
from markitdown import MarkItDown

md = MarkItDown(enable_plugins=True)     # same as the -p flag of the command line
print(md.convert("samples/notes.txt").markdown.splitlines()[0])
print("installed third-party plugins are loaded from the 'markitdown.plugin' entry-point group")
Output · markitdown 0.1.9 · Python 3.13.18 · 2026-11-15
Plain text notes.
installed third-party plugins are loaded from the 'markitdown.plugin' entry-point group

captured result

Converter order is set by priority; lower numbers run first and the newest registration wins a tie:

Pythonapi-priority.py
from markitdown import DocumentConverter, DocumentConverterResult, MarkItDown, PRIORITY_SPECIFIC_FILE_FORMAT, PRIORITY_GENERIC_FILE_FORMAT

print("PRIORITY_SPECIFIC_FILE_FORMAT =", PRIORITY_SPECIFIC_FILE_FORMAT)
print("PRIORITY_GENERIC_FILE_FORMAT  =", PRIORITY_GENERIC_FILE_FORMAT)

def make(label):
    class C(DocumentConverter):
        def accepts(self, file_stream, stream_info, **kw): return (stream_info.extension or "") == ".txt"
        def convert(self, file_stream, stream_info, **kw): return DocumentConverterResult(markdown=label)
    return C()

md = MarkItDown()
md.register_converter(make("registered first, priority 0"), priority=0.0)
md.register_converter(make("registered second, priority 0"), priority=0.0)
print("equal priority, newest wins:", md.convert("samples/notes.txt").markdown)
md.register_converter(make("registered last, priority 100"), priority=100.0)
print("larger number runs later:", md.convert("samples/notes.txt").markdown)
Output · markitdown 0.1.9 · Python 3.13.18 · 2026-11-15
PRIORITY_SPECIFIC_FILE_FORMAT = 0.0
PRIORITY_GENERIC_FILE_FORMAT  = 10.0
equal priority, newest wins: registered second, priority 0
larger number runs later: registered second, priority 0

captured result

Pythonapi-custom-converter.py
from markitdown import DocumentConverter, DocumentConverterResult, MarkItDown, StreamInfo, PRIORITY_SPECIFIC_FILE_FORMAT

class WordCountConverter(DocumentConverter):
    """Turns any .txt file into a one-line word count."""
    def accepts(self, file_stream, stream_info: StreamInfo, **kwargs) -> bool:
        return (stream_info.extension or "").lower() == ".txt"

    def convert(self, file_stream, stream_info: StreamInfo, **kwargs) -> DocumentConverterResult:
        text = file_stream.read().decode(stream_info.charset or "utf-8")
        return DocumentConverterResult(markdown=f"{len(text.split())} words", title="Word count")

md = MarkItDown()
print("before:", md.convert("samples/notes.txt").markdown.splitlines()[0])
md.register_converter(WordCountConverter(), priority=PRIORITY_SPECIFIC_FILE_FORMAT - 1)
result = md.convert("samples/notes.txt")
print("after:", result.markdown, "| title:", result.title)
Output · markitdown 0.1.9 · Python 3.13.18 · 2026-11-15
before: Plain text notes.
after: 9 words | title: Word count

captured result

Performance and reuse

Pythonapi-reuse-timing.py
import time
from markitdown import MarkItDown

t = time.perf_counter(); md = MarkItDown(); build = time.perf_counter() - t
times = []
for _ in range(5):
    t = time.perf_counter(); md.convert("samples/report.docx"); times.append(time.perf_counter() - t)
t = time.perf_counter()
for _ in range(5): MarkItDown().convert("samples/report.docx")
fresh = (time.perf_counter() - t) / 5
print(f"construct once: {build:.3f} s")
print(f"first convert: {times[0]:.3f} s, later converts: {min(times[1:]):.3f} to {max(times[1:]):.3f} s")
print(f"new converter for every call: {fresh:.3f} s per conversion")
Output · markitdown 0.1.9 · Python 3.13.18 · 2026-11-15
construct once: 0.036 s
first convert: 0.230 s, later converts: 0.138 to 0.322 s
new converter for every call: 0.200 s per conversion

captured result

Building the converter is cheap (about 0.04 s on our machine) and the first conversion is the slowest, so for small files reuse barely changes the time. Reuse it anyway, because plugins and an LLM client are set up once. One instance shared by eight threads converted 120 files with output identical to the serial run:

Pythonapi-thread-safety.py
import concurrent.futures as cf, hashlib
from markitdown import MarkItDown

files = ["samples/report.docx", "samples/deck.pptx", "samples/workbook.xlsx", "samples/data.csv", "samples/page.html", "samples/pdf-text.pdf"] * 20
md = MarkItDown()
serial = [hashlib.sha256(md.convert(f).markdown.encode()).hexdigest() for f in files]
with cf.ThreadPoolExecutor(8) as pool:
    threaded = list(pool.map(lambda f: hashlib.sha256(md.convert(f).markdown.encode()).hexdigest(), files))
print("conversions:", len(files))
print("identical to the serial run:", serial == threaded)
Output · markitdown 0.1.9 · Python 3.13.18 · 2026-11-15
conversions: 120
identical to the serial run: True

captured result

For processes see batch conversion. Notebooks and Colab: we did not test them.

Warnings and logging

Installing the audio extra makes Python print the ffmpeg warning when the audio library is imported with warnings enabled (what it means). Type hints ship with the package.

Common mistakes

  • Naming your own file markitdown.py: it shadows the package.

Reproduced by us

ImportError: cannot import name 'MarkItDown' from partially initialized module 'markitdown' (most likely due to a circular import)

Your own file is called markitdown.py (or sits in a folder called markitdown), so Python imports it instead of the library. The wording depends on the Python version: 3.10 to 3.12 say 'partially initialized module', 3.13 and later suggest renaming the file.

Affected: any · last reproduced 2026-11-15 · Upstream report

  • Using old argument names from older tutorials: on old releases llm_client raised a TypeError (error index), and on 0.1.9 the deprecated file_extension and url arguments of convert_stream still work:
Pythonapi-deprecated-args.py
import io
from markitdown import MarkItDown

data = open("samples/data.csv", "rb").read()
r1 = MarkItDown().convert_stream(io.BytesIO(data), file_extension=".csv")
r2 = MarkItDown().convert_stream(io.BytesIO(data), url="https://example.org/data.csv")
print(r1.markdown == r2.markdown)
print(r1.markdown.splitlines()[0])
Output · markitdown 0.1.9 · Python 3.13.18 · 2026-11-15
True
| station | rainfall_mm | notes |

captured result

  • Calling convert on user input (see the warning above).
  • Printing the result on Windows and redirecting it, instead of writing UTF-8 files (encoding).
  • Expecting an exception for a scanned PDF.