File names with slashes [was Re: error in os.chdir]

Richard Damon Richard at
Sun Jul 1 11:42:16 EDT 2018

On 7/1/18 6:49 AM, Mikhail V wrote:
> [Steven D'Aprano]
>> (The same applies to Unix/Linux systems too, of course.) But while you're
>> using Python to manipulate files, you should use Python rules, and that
>> is "always use forward slashes".
>> Is that reasonable?
>> Under what circumstances would a user calling open(pathname) in Python
>> need to care about backslashes?
> Cough cough
> On Windows a path is e.g.:
> C:\programs\util\
> So why should I use forward slashes in a Python literal?
> I don't remember any problem caused by using backslashes in paths in Python -
> are there problems?
> (Apart from the fact that Python dos not have true raw string literals)
> So what is reasonable about using forward slashes?
> It happens to me that I need to copy-paste real paths like 100 times
> a day into scripts - do you propose to convert to forward slashes each time?

The one major issue with backslashes is that they are a special
character in string literals, so you either need to use raw literals a
remember the few cases they still act as special characters, or remember
to convert them to double back slashes, at a minimum for all the
characters that they are special for (easier to double them all).

I think it was originally an error to make the backslash followed by a
character not defined as special with a backslash as keeping the
backslash as a literal as it causes a number of these issues. Yes, it
allows you to not need to double it in many cases but that just sets you
up for the mistakes that started the thread. It is probably too late to
change that behavior now though.

Richard Damon

More information about the Python-list mailing list