[Tutor] creating files with python and a thanks

dman dsh8290@rit.edu
Sun, 17 Feb 2002 19:40:40 -0500

On Sun, Feb 17, 2002 at 05:45:11PM -0500, Erik Price wrote:
| On Saturday, February 16, 2002, at 09:37  AM, Sheila King wrote:
| >f = open(r'c:\windows\temp\myfile.mbg', 'w')
| >f.write('this is my file\nmy stuff\nis in\nmy\nfile')
| >f.close()
| >
| >(I used the r in front of the quotes, so that it will interpret the
| >string as a "raw" string, and not assume the \t on \temp represents the
| >escape sequence for a tab character.)
| A quick question on this 'r' flag:
| I use a unix-style filesystem, so I wouldn't have the same problem as 
| above (it would be './temp/myfile.mbg', and I'm making the assumption 
| that /t has no special meaning, though it might).

Right.  In paths, forward slashes are Good and backslashes are Evil.

| But is it generally good practice to use the 'r' flag like this when
| you have no intention of using variable/shell expansion?
| In PHP, as well as Bash programming, single quotes are used for when you 
| wish this effect -- a 'literal' string.  But double-quotes are used when 
| you are okay with \t matching [tab] and other meta-characters.  Judging 
| from this example, the Python equivalent is using 'open(r'string', 'w')'.
| Do you try to always use the 'r' option -except- when you want 
| expansion, or is the general practice to only use it when you -need- it 
| to prevent a metacharacter like \t from being expanded?

If your string contains special characters (backslashes) but you don't
want them treated specially, use the 'r' flag.  Otherwise don't



Who can say, "I have kept my heart pure;
I am clean and without sin"?
        Proverbs 20:9