Reputation: 2580
Currently I use os.path.join
almost always in my django project for cross OS support; the only places where I don't currently use it are for template names and for URLs. So in situations where I want the path '/path/to/some/file.ext'
I use os.path.join('path', 'to', 'some', 'file.ext')
.
However I just tested my project on windows to see whether that worked fine / was necessary and it seems windows will happily accept '/'
or '\\'
(or '\'
when working outside of python), and as all UNIX systems all use '/'
it seems like there is no reason to ever use '\\'
, in which case is it necessary to use os.path.join
anywhere?
Is there a situation in which adding a '/'
or using posixpath
will cause problems on certain operating systems (not including XP or below as they are no longer officially supported)? If not I think I will just use posixpath
or adding a '/'
for joining variables with other variables or variables with strings and not separate out string paths (so leave it as '/path/to/some/file.ext'
) unless there is another reason for me to not do that other than it breaking things.
To avoid this being potentially closed as primarily-opinion based I would like to clarify that my specific question is whether not using os.path.join
will ever cause a python program to not work as intended on a supported operating system.
Upvotes: 12
Views: 2509
Reputation: 70735
The Microsoft Windows API doesn't care whether you use /
or \
, so it's normally fine to use either as a separator on Windows. However, command line ("DOS box" - command.com
or cmd.exe
) commands generally require \
in paths (/
is used to flag command options in these native Windows shells). So, for example, if you build a command line in Python and fire off a shell to execute the command, you'll generally need to use the \
separator on Windows.
One other case is covered in Lib/macpath.py
: there sep
is set to :
(a colon), catering to older Macintosh systems. I believe that's the only system Python has ever run on that doesn't accept /
as a separator.
EDIT: see here for a long account of Windows naming rules. Don't blame me ;-)
Upvotes: 16
Reputation: 308530
If you are presenting a filename to a user for any reason, it's better if that filename follows the usual OS conventions.
Windows has been able to use the /
for path separators for as long as there have been paths - this was a DOS feature.
Upvotes: 4