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?
To find the current working directory in Python, use os. getcwd() , and to change the current working directory, use os. chdir(path) .
How to create a string in Python? Strings can be created by enclosing characters inside a single quote or double-quotes. Even triple quotes can be used in Python but generally used to represent multiline strings and docstrings.
Python raw string is created by prefixing a string literal with 'r' or 'R'. Python raw string treats backslash (\) as a literal character. This is useful when we want to have a string that contains backslash and don't want it to be treated as an escape character.
To change the current working directory(CWD) os. chdir() method is used. This method changes the CWD to a specified path. It only takes a single argument as a new directory path.
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.path
will 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 from os.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.
I would advise to use forward slashes or double backslashes. A raw string, as sugested by ThiefMaster, can be tricky; it can, for example, not end with a backslash; so r'c:\foo\' is not a valid raw string.. See python docs:
r"\" is not a valid string literal (even a raw string cannot end in an odd number of backslashes). Specifically, a raw string cannot end in a single backslash (since the backslash would escape the following quote character)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With