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

Chris Angelico rosuav at gmail.com
Wed Jul 4 16:30:23 EDT 2018


On Thu, Jul 5, 2018 at 6:25 AM, Mikhail V <mikhailwas at gmail.com> wrote:
> Joe Pfeiffer wrote:
>
>>> On Windows a path is e.g.:
>>> C:\programs\util\
>>> 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?
>
>> That's what started the thread -- using backslashes caused a \a to be
>> interpreted as a special character instead of two characters in the
>> path.
>
> Yes, and the answer was a week ago: just put "r" before  the string.
> r"C:\programs\util"
>
> And it worked till now. So why should I replace backslashes with
> forward slashes?
> There is one issue that I can't write \ on the end:
> r"C:\programs\util\"
>
> But since I know it's a path and not a file, I just write without trailing \.

That's exactly the issue. But if you just always separate paths with
forward slashes, you never have a problem. There is no "replace"
happening; you simply use the correct path separation character from
the start. You can assemble strings from pieces without having to
remember to slap an "r" in front of each literal; you can have slashes
at the ends of strings; everything will just work.

ChrisA



More information about the Python-list mailing list