0

How to force Python to use / as path separator (for glob, os.path, etc.), even on Windows?

I tried os.sep = '/' but it does not work:

import os, glob
os.sep = '/'
os.path.sep = '/'

for f in glob.glob('D:/Temp/**/*', recursive=True):
    print(f)
# D:/Temp\New folder
# D:/Temp\New Text Document.txt    

print(os.path.join('D:/', 'Temp', 'hello'))
# D:/Temp\hello

I'd like to avoid "hacks" like having to add .replace('\\', '/') for each path, so linked questions like Why not os.path.join use os.path.sep or os.sep? don't answer it.

I also tried:

import posixpath as path
print(path.normpath(path.join('D:\\Temp', 'hello')))
# D:\Temp/hello    # path.join has correctly use forward slashes

but here \isn't replaced by /.

Basj
  • 41,386
  • 99
  • 383
  • 673
  • Why do you want this? – Thomas Dec 03 '20 at 16:27
  • I'm coding a backup tool @Thomas that works with Linux remotes, so I want to have a way to represent filenames/paths that is independant if local OS is Win or Unix. – Basj Dec 03 '20 at 16:32
  • You shouldn't import posixpath like that on Windows. And if you do, it doesn't surprise me that normpath no longer treats it correctly as it does nothing on Linux in regards to slashes. You are viewing replacing ` \ ` with `/` as a hack, but on Windows, both are accepted as slashes, so it is a fairly safe approach to normalizing those paths. I would put a Windows specific conditional around it because on Linux, ` \ ` can be used as a non-path separator. You can try using pathlib to abstract paths, but there is no way to just tell Python to always use `/` on Windows in stdlib functions. – facelessuser Dec 03 '20 at 16:53
  • https://docs.python.org/3/library/pathlib.html#pathlib.PurePosixPath – Thomas Dec 04 '20 at 10:02

0 Answers0