1

When I try the following code:

a = "C:\Python27\777.xls"
print a

I get this error:

Decode error- output not utf-8

Although there are other questions which seem related, they mostly seem to be from people actually trying to encode something, whereas I am just trying to make sure my file path does not error out when I call it.

How can I fix it?

1 Answer 1

4

You need to escape your slashes: write \\ instead of just \ when you want a backslash.

a = "C:\\Python27\\777.xls"
print a

Alternatively, you could use a "raw string." Whenever a string is a raw string, a slash i just a slash, and you don't have to worry about weird stuff happening.

a = r"C:\Python27\777.xls"
print a

Right now, Python is interpreting the \777 as a single character, with the octal value 777, which does not exist. So Python is puking. Check out this link to the reference and scroll down a bit for the escape sequences in Python strings. https://docs.python.org/3/reference/lexical_analysis.html#strings

Sign up to request clarification or add additional context in comments.

2 Comments

Works! However just in case someone runs into the problem i wanted to point out that if someone did: a = "C:\Python27\helloworld" print a, it would actually print a statement. Is it just better practice to perhaps 'always' use the backslash?
Yeah, it's always best practice to use the backslash (PS, this is called "escaping" the backslash). You can also use what is called a "raw string", and that's just as good. I'll update my answer to explain a raw string.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.