Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python: 'unicodeescape' codec can't decode bytes in position

The unicodeescape SyntaxError comes from backslashes in a normal string: escapes such as U, u and x get decoded. Raw strings or pathlib avoid it.

~5 min readPython
#python#syntaxerror#strings#pathlib
Bold white headline reading BAD ESCAPE with a Python string crate holding an amber backslash path card on the right.

Introduction & Quick Summary

Python refuses to parse a file, pointing at a string literal:

code
File "app.py", line 3 path = "C:\Users\name\data" ^^^^^^^^^^^^^^^^^^^^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

The caret is not on a syntax you wrote; it is on an escape sequence Python tried to decode and could not. \U begins an eight-hex-digit escape, C:\Users supplies \U followed by sers, and sers is not eight hex digits. The same class of failure covers \x (two hex digits), \u (four), and \N{NAME} (a Unicode character name).

Quick answer: the string is a path, not data with escapes, so make that explicit.

python
path = r"C:\Users\name\data" # raw string: backslashes are literal path = "C:/Users/name/data" # forward slashes: Windows accepts them path = Path(r"C:\Users\name\data") # pathlib, which also joins safely path = "C:\\Users\\name\\data" # escaped, the noisiest of the four

For a whole-file fix, prefer Path: it removes the question of separators and gives you / joining, .exists(), and .read_text() without a second library.

The same error appears for regex patterns ("\d+"), Windows paths in configuration files, SQL snippets containing \N, and docstrings with \N{EM DASH} in a function that also uses \n.

Core Mechanics, Signatures & Reproducible Setup

Python decodes escape sequences while it parses the literal, before the program runs. The complete set that can raise this error:

EscapeConsumesValid exampleError when malformed
\xexactly 2 hex digits"\x41"truncated \xXX escape
\uexactly 4 hex digits"\u00e9"truncated \uXXXX escape
\Uexactly 8 hex digits"\U0001F600"truncated \UXXXXXXXX escape
\N{NAME} from Unicode data"\N{BULLET}"malformed \N character escape
\\, \', \"one character"C:\\tmp"n/a
\n, \t, \rone control character"a\nb"n/a
anything elsethe two characters, unchanged"\d"a SyntaxWarning since 3.12

Reproduce all four in one file, which is worth keeping as a test fixture:

python
print("\x41") # A print("\u00e9") # é print("\U0001F600") # 😀 print("\N{BULLET}") # • # each of these raises SyntaxError at parse time # "C:\Users\name" # "\Nope" # "\u12"

Raw strings are the general-purpose fix: r"..." disables escape processing entirely. One restriction makes them unsuitable for every case — a raw string cannot end in a single backslash (r"dir\" is a syntax error, because the backslash escapes the quote), and Windows paths ending in \ are exactly that shape. os.path.join or Path avoids the problem:

python
from pathlib import Path base = Path(r"C:\Users\name") target = base / "data" / "file.csv" # no trailing separator to escape

Key Comparison Table

Four ways to write a Windows path, with what each costs:

FormExampleProsCons
raw stringr"C:\Users\me"exact text, no escapingcannot end with \
forward slashes"C:/Users/me"portable, works on Windows APIsbreaks if the string is not a path
pathlib.PathPath(r"C:\Users\me")joins, existence checks, no doublingobject, not a string at the boundary
doubled backslash"C:\\Users\\me"plain str resultunreadable, easy to miss one

The error variants and their trigger character:

Message fragmentOffending sequenceFix
truncated \UXXXXXXXX escape\U plus fewer than 8 hex digitsraw string or forward slashes
truncated \uXXXX escape\u plus fewer than 4 hex digitsraw string
truncated \xXX escape\x plus fewer than 2 hex digitsraw string
malformed \N character escape\N without {NAME}escape the backslash, or use \u
SyntaxWarning: invalid escape sequence '\d'any unknown escape (3.12+)raw string for regex

Where the string usually comes from:

SourceTypical textBetter approach
pasted Windows pathC:\Users\...Path or forward slashes
regex pattern inline\d{4}-\d{2}re.compile(r"...")
config file valueC:\logs\app.logread as-is; escapes are not processed there
SQL or JSON snippet\N, \"read from a file, not a literal
docstring\N{...}raw docstring r"""..."""

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. The pasted path, and why file and path differ

python
# fails: \U is an escape log = open("C:\Users\me\logs\app.log") # works, and stays readable from pathlib import Path log = Path("C:/Users/me/logs/app.log").open(encoding="utf-8") # works, on any platform log = Path.home() / "logs" / "app.log"

The third form is the one to prefer in application code: it resolves the home directory per platform, and it never contains a backslash to escape.

2. Regex patterns are the second most common case

python
# warns in 3.12+, breaks in 3.13 with -W error m = re.match("\d{4}-\d{2}-\d{2}", text) # correct pattern = re.compile(r"\d{4}-\d{2}-\d{2}") m = pattern.match(text)

\d is not a valid escape, so Python keeps it as two characters and the regex engine sees what you meant — which is why this code can run for years and then start emitting SyntaxWarning: invalid escape sequence '\d'. Raw strings remove the ambiguity, and compiling once also avoids re-parsing the pattern on every call.

3. f-strings, backslashes and version differences

Before Python 3.12, a backslash was not allowed inside an f-string expression at all:

python
# SyntaxError before 3.12 name = f"{'C:\\tmp'}" name = f"{r'C:\tmp'}" # workaround that still works everywhere

PEP 701 lifted that restriction in 3.12, so the first line is legal there and rejected on 3.11 and older. Code meant to run on both should use the raw-string form, or build the path outside the f-string.

4. Raw strings that cannot exist

python
# SyntaxError: a raw string cannot end with an odd number of backslashes root = r"C:\temp\" # three options root = "C:\\temp\\" root = r"C:\temp" + "\\" root = str(Path("C:/temp"))

The third is the clearest when the value is a directory, and it composes with / for children.

5. Values that arrive from outside the source

Escapes are a property of the literal, not of the data. A path read from config.ini, JSON, or an environment variable contains real backslashes and needs no fix:

python
import json, os cfg = json.loads(open("config.json", encoding="utf-8").read()) root = cfg["root"] # already decoded, no escape processing same = os.environ["APP_ROOT"] # same here

When a value does need decoding, use codecs.decode(value, "unicode_escape") deliberately — and note it mangles non-ASCII text by treating it as Latin-1.

6. Turning the warning into a build failure

bash
python -W error::SyntaxWarning -c "import app" # 3.12+ python -X dev -m compileall -q src # shows every invalid escape

Finding all of them at once is a one-liner with a pattern search, and the regular expression tester confirms it matches \d, \w, \s, and \U forms without catching legitimate \\n. When a config value is suspected, the JSON formatter shows whether the backslashes in the file are doubled, which is the difference between a correct value and a broken one.

Common Compilation/Runtime Mistakes & Version Gotchas

Doubling every backslash by hand. "C:\\Users\\me\\new" is easy to get wrong, and a missing pair produces either a silent \n, \t, or \r in the path or the same error one line later. Raw strings and Path remove the class of bug instead of one instance.

Wrapping a string that already contains escapes in r. r"\n" is a backslash and an n, not a newline. Applying r to a string that relied on \n changes behaviour silently — the fix for a path should not be pasted onto log messages.

Assuming \d in a normal string is harmless forever. It is today, with a warning since 3.12. Running with -W error or on a future Python where invalid escapes become errors turns every one of them into a hard failure at import time.

Version differences. Python 3.6 introduced f-strings; 3.8 made SyntaxWarning appear for invalid escapes in some contexts; 3.12 raised it to a warning in all contexts and added PEP 701. Python 3.13 continues to warn rather than fail, so the code keeps running — which is exactly why auditing is better than waiting. ast.parse with feature_version is the practical way to test compatibility across versions without installing each one.

Byte strings behave differently. b"\u00e9" is not an escape in a bytes literal; it is six literal characters, and b"\x41" is a single byte. Mixing the two mental models is common when a path is passed to os.open — decode at the boundary and keep the escape question in one place.

Reference material: String and Bytes Literals and the Unicode HOWTO.

Official references

primary documentation

The Python documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.