This small script reads a list of URLs and writes an XML sitemap. It uses only the standard library of Python.
from datetime import date
from xml.sax.saxutils import escape
def build_sitemap(urls, lastmod):
lines = ['<?xml version="1.0" encoding="UTF-8"?>',
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">']
for url in urls:
lines.append(" <url>")
lines.append(" <loc>" + escape(url) + "</loc>")
lines.append(" <lastmod>" + lastmod + "</lastmod>")
lines.append(" </url>")
lines.append("</urlset>")
return "\n".join(lines)
with open("urls.txt") as f:
urls = [line.strip() for line in f if line.strip()]
xml = build_sitemap(urls, date(2026, 9, 1).isoformat())
with open("sitemap.xml", "w", encoding="utf-8") as f:
f.write(xml + "\n")
print(len(urls), "URLs written to sitemap.xml")
Output
$ python3 make_sitemap.py
4 URLs written to sitemap.xml
$ cat sitemap.xml
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://example.com/</loc>
<lastmod>2026-09-01</lastmod>
</url>
<url>
<loc>https://example.com/seo-introduction/</loc>
<lastmod>2026-09-01</lastmod>
</url>
<url>
<loc>https://example.com/seo-title-tag/</loc>
<lastmod>2026-09-01</lastmod>
</url>
<url>
<loc>https://example.com/seo-robots-txt/</loc>
<lastmod>2026-09-01</lastmod>
</url>
</urlset>
$ xmllint –noout sitemap.xml && echo "sitemap.xml is valid XML"
sitemap.xml is valid XML
How it works
- The script reads one URL per line from
urls.txt. escape() changes the special characters like & in URLs, so the XML stays valid.- It writes a
loc and a lastmod for each page. Use the real date of the last change for each page, not always today. xmllint is a tool to check that the XML is well formed.
Note:
A sitemap file can have at most 50,000 URLs and 50 MB. For more URLs, make many files and a sitemap index. See XML Sitemap.
Learn more about the similar topics:
| Tutorials |
| No Content Found. |
| Exercises & Assignments |
| No Content Found. |
| Interview Questions & Answers |
| No Content Found. |