Unicode error in Python when trying to open a file on Windows

When trying to open a file on Windows using Python’s open() function I came across a little error that wouldn’t allow me to open the file. The error was as follows:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape

It turned out the file path I was using (C:\Users\......\SWAN\A1PelamisWave) has a couple of \U’s in it which apparently represents a unicode escape. To resolve this I placed an ‘r’ in front of the file string as follows:

file = open(r'C:\Users\......\SWAN\A1PelamisWave', 'r');

This causes Python to treat it as a raw string. The answer was found in this helpful StackOverflow post.

Published by:


Software Developer at UKFast Ltd. Previously Web Applications Developer at SenseLogix Ltd. Graduate of Renewable Energy BSc from the University of Exeter. Experience with PHP, MySQL, Javascript, CSS and HTML. Familiarity with systems administration on CentOS and Debian.

Categories Programming, Python, WindowsTags , Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s