Sunday, September 4, 2011

Python: Open with Raw Strings

When you open a file on a windows system in Python, your command may look something like this:

open("C:\Users\...\file.yml"...)

The problem is that the windows slashes will make the following characters special. You have two options:

1) You can escape each slash with another slash:
open("C:\\Users\\...\\file.yml"...)

2) You can use a raw string. Raw strings don't let the slash modify anything, they just take the string as is. You signal them with a naked r right in front of the string, like so:

open(r"C:\Users\...\file.yml"...)

You also need to specify how to open the file (see the open command). I just want to read the file, so I often do this:

open(r"C:\Users\directory\file.yml",r)

But wait! Suddenly I get an error! Python is complaining about my r:

"NameError: name 'r' is not defined"

I start to panic. Maybe raw string support broke in the latest version of Python!

It takes me about 15 minutes of furious googling before I realize my mistake. The signal for the open command, that's the 'r' causing a problem. The first r is naked, unquoted. But the open command's argument is still a string, it still needs some sort of quotation mark.

The correct line is:

open(r"C:\Users\directory\file.yml",'r')

Hopefully I'll remember to reread this post first next time...

No comments:

Post a Comment