5

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?

2 Answers 2

8

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.

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

1 Comment

I've been programming in Python for a few months now and I didn't know about raw strings. Very helpful, thanks.
8

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)

3 Comments

Good point. It happens that all my directories will in fact be files ending in .txt or .pdf or something, so I think it is safe for me to use raw strings in this case. It solves my main problem of just wanting to copy and paste directories from Windows Explorer.
Forward slashes have one disadvantage though: As soon as you use os.path.join() and similar methods, they will introduce backslashes. The mix looks ugly but if you never show it to the user without normalizing slashes it doesn't matter. If you have to display it to the user, consider using os.path.normpath() first
@ThiefMaster A string replace afterwards takes care of that. Not pretty, but better than leaving the mixed string in existence.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.