I have a list of directories hard coded into my program as such:
import os
my_dirs = ["C:\a\foo"
,"C:\b\foo"
,"C:\c\foo"
,"C:\t\foo"
]
I later want to perform some operation like os.path.isfile(my_dirs[3]). But the string my_dirs[3] is becoming messed up because "\t" is short for tab or something.
I know that a solution to this would be to use this:
my_dirs = ["C:\\a\\foo"
,"C:\\b\\foo"
,"C:\\c\\foo"
,"C:\\t\\foo"
]
And another solution would be to use forward slashes.
But I like being able to copy directories straight from explorer to my Python code. Is there any way I can tell Python not to turn "\t" into a tab or some other solution to my problem?
Use forward slashes or raw strings:
r'C:\a\foo'or'C:/a/foo'Actually, using forward slashes is the better solutions since as @Wesley mentioned, you cannot have a raw string ending in a single backslash. While functions from
os.pathwill use backslashes on windows, mixing them doesn’t cause any problems – so i’d suggest to use forward slashes in hardcoded paths and don’t care about the backslashes introduced by functions fromos.path.Don’t forget that hardcoded paths are a bad thing per se though. Especially if you use system folders (including “My Documents” and “AppData”) you should rather use WinAPI functions to retrieve them no matter where they are actually located.