Including rst files into rst files is easy. But what about a markdown readme that also lives in a different directory tree?

My python projects have the following structure:

I usually want to include my also in the documentation that is rendered with sphinx and hosted at readthedocs.

If the readme was formatted as a RST file, this would be no problem: Create another readme.rst in the doc folder and use the include directive to include the readme from the directory above. You would even have fine grained control over which parts of the file to include.

However, the allcontributors bot still doesn’t work with rst files (issue), so I’m bound to markdown if I want to use it.

There are several suggestions out there, but the only elegant one seems to involve the m2r package (github) which however is no longer maintained and doesn’t seem to work with the newer sphinx versions.

My current workaround is to add the following in

  1. Add recommonmark to the list of extensions
  2. Set source_suffix = [".rst", ".md"]
  3. Add the following snippet:
import pathlib

# The readme that already exists

readme_path = pathlib.Path(**file**).parent.resolve().parent / ""

# We copy a modified version here

readme_target = pathlib.Path(**file**).parent / ""

with"w") as outf: # Change the title to "Readme"
lines = []
for line in readme_path.read_text().split("\n"):
if line.startswith("# "): # Skip title, because we now use "Readme" # Could also simply exclude first line for the same effect

You can see it in action at the AnkiPandas documentation.

You might also enjoy reading this discussion on github that discusses some other approaches (many of which don’t work).

Note: Updated on Mai 23 2021 with an improved version.