Python “unicodeescape codec can't decode”: use a raw string for paths
Prefix the string with r to make it raw, or use forward slashes in the path.
Windows paths contain backslash escapes (\U, \n). Make the string raw — r"C:\Users\new" — or use forward slashes: "C:/Users/new". A raw string cannot end in a single backslash, so r"C:\dir\" is still invalid.
Try these fixes in order
Use a raw string
The r prefix tells the tokenizer to leave backslashes alone. This is the standard fix for Windows paths.
Or use forward slashes
Python accepts forward slashes as separators on Windows, which removes the escape problem at the source.
path = "C:/Users/new/file.txt"Or double the backslashes
If you must keep backslashes in a regular string, escape each one by doubling it.
path = "C:\\Users\\new\\file.txt"Re-run and confirm
Re-run the script; the SyntaxError at the literal is gone and the path resolves correctly.
python script.pyInterpret what you see
The path contains \U, \n, \t, or \r sequences
What it suggests: \U starts a 8-digit Unicode escape, so C:\Users is parsed as an escape and fails. \n and \t silently become newline and tab instead of erroring.
Next check: Rewrite the literal as a raw string: r"C:\Users\new".
The traceback points at the string literal line
What it suggests: This error appears at import/parse time, before any code runs, because it is the tokenizer rejecting the literal.
Next check: Fix the literal itself; no runtime setting changes this.
You control the path string
What it suggests: Forward slashes work as path separators on Windows in Python, avoiding backslashes entirely.
Next check: Write the path as "C:/Users/new".
Why this happens
- A Windows path like C:\Users\new contains backslash sequences (\U, \n) that Python reads as string escapes.
- The string is not marked raw, so every backslash is interpreted as the start of an escape sequence.
Still not working?
Do not fix this by doubling some backslashes and leaving others; mixed escaping is fragile and breaks the next time the path changes. Use a raw string or forward slashes consistently.
Official sources
These steps are based on the linked documentation and general diagnostics. BugMedic has not independently tested every product and system configuration. Review commands before running them.