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.

Introduction & Quick Summary
Python refuses to parse a file, pointing at a string literal:
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 escapeThe 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.
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 fourFor 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:
| Escape | Consumes | Valid example | Error when malformed |
|---|---|---|---|
\x | exactly 2 hex digits | "\x41" | truncated \xXX escape |
\u | exactly 4 hex digits | "\u00e9" | truncated \uXXXX escape |
\U | exactly 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, \r | one control character | "a\nb" | n/a |
| anything else | the two characters, unchanged | "\d" | a SyntaxWarning since 3.12 |
Reproduce all four in one file, which is worth keeping as a test fixture:
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:
from pathlib import Path
base = Path(r"C:\Users\name")
target = base / "data" / "file.csv" # no trailing separator to escapeKey Comparison Table
Four ways to write a Windows path, with what each costs:
| Form | Example | Pros | Cons |
|---|---|---|---|
| raw string | r"C:\Users\me" | exact text, no escaping | cannot end with \ |
| forward slashes | "C:/Users/me" | portable, works on Windows APIs | breaks if the string is not a path |
pathlib.Path | Path(r"C:\Users\me") | joins, existence checks, no doubling | object, not a string at the boundary |
| doubled backslash | "C:\\Users\\me" | plain str result | unreadable, easy to miss one |
The error variants and their trigger character:
| Message fragment | Offending sequence | Fix |
|---|---|---|
truncated \UXXXXXXXX escape | \U plus fewer than 8 hex digits | raw string or forward slashes |
truncated \uXXXX escape | \u plus fewer than 4 hex digits | raw string |
truncated \xXX escape | \x plus fewer than 2 hex digits | raw 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:
| Source | Typical text | Better approach |
|---|---|---|
| pasted Windows path | C:\Users\... | Path or forward slashes |
| regex pattern inline | \d{4}-\d{2} | re.compile(r"...") |
| config file value | C:\logs\app.log | read 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
# 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
# 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:
# SyntaxError before 3.12
name = f"{'C:\\tmp'}"
name = f"{r'C:\tmp'}" # workaround that still works everywherePEP 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
# 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:
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 hereWhen 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
python -W error::SyntaxWarning -c "import app" # 3.12+
python -X dev -m compileall -q src # shows every invalid escapeFinding 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 documentationThe Python documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython Typer Rich Integration and Progress Bars
python typer rich integration and progress bars: Learn to integrate Rich progress bars into Typer CLI applications, covering track, Progress, dynamic.
asyncpg DuplicatePreparedStatement on PgBouncer and Supabase
asyncpg caches prepared statements per connection while a transaction pooler rotates connections underneath it. The cache setting, pool sizing and retry.
Python Tabulate: Markdown Grid Headers and Alignment
Use Python's tabulate library to format Markdown tables, set custom headers, and control column alignment with pipe and grid formats.
Python Watchdog Created, Modified, and Deleted Events
Handle created, modified, and deleted file events with Python's watchdog library. Covers handler methods, event objects, duplicate modification events.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.