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.