How to Use "/" (Directory Separator) in Both Linux and Windows in Python

How to use / (directory separator) in both Linux and Windows in Python?

Use os.path.join().
Example: os.path.join(pathfile,"output","log.txt").

In your code that would be: rootTree.write(os.path.join(pathfile,"output","log.txt"))

Path Separator in Python 3

Yes, python provides os.sep, which is that character, but for your purpose, the function os.path.join() is what you are looking for.

>>> os.path.join("data", "foo1")
"data/foo1"

How to get the PATH environment-variable separator in Python?

os.pathsep

mixed slashes with os.path.join on windows

You are now providing some of the slashes yourself and letting os.path.join pick others. It's better to let python pick all of them or provide them all yourself. Python uses backslashes for the latter part of the path, because backslashes are the default on Windows.

import os

a = 'c:' # removed slash
b = 'myFirstDirectory' # removed slash
c = 'mySecondDirectory'
d = 'myThirdDirectory'
e = 'myExecutable.exe'

print os.path.join(a + os.sep, b, c, d, e)

I haven't tested this, but I hope this helps. It's more common to have a base path and only having to join one other element, mostly files.

By the way; you can use os.sep for those moments you want to have the best separator for the operating system python is running on.

Edit: as dash-tom-bang states, apparently for Windows you do need to include a separator for the root of the path. Otherwise you create a relative path instead of an absolute one.

What is the difference between using / and \\ in specifying folder location in python?

On Unix systems, the folder separator is /, while on Windows systems, the separator is \. Unfortunately this \ is also an escape character in most programming languages and text based formats (including C, Python and many others). Strangely enough a / character is not allowed in windows paths.

So Python on windows is designed to accept both / and \ as folder separator when dealing with the filesystem, for convenience. But the \ must be escaped by another \ (unless of course you use raw strings like r'backslashes are now normal characters \\\ !')

Selenium, on the other hand, will write values into Firefox preferences, which, unlike Python, expects the appropriate kind of separator. That's why using forward slashes does not work in your example.

Why not os.path.join use os.path.sep or os.sep?

Why not define a custom display function?

e.g.

def display_path(path):
return path.replace("\\", "/")

And if you want to substitute str.join for os.path.join, you can just do this (str.join expects a single list, os.path.join expects *args):

join = lambda *args: "/".join(args)

Perhaps better would be to let Python normalize everything, then replace, e.g.:

join = lambda *args: os.path.join(*args).replace("\\", "/")

The only issue with the above might be on posix when there is a space in the file path.

You could then put an if statement at the top of your utils file and define display_path and join as a no-op and as os.path.join respectively if not on Windows.

path compatible for both windows and linux

Try changing the filename timestamp format since in Windows OS filenames can't contain colons : as mentioned in comments by John Gordon

So instead of

import datetime
from os.path import dirname, abspath, join, exists
logs_folder = join(dirname(dirname(abspath(__file__))), 'logs')
file_name = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")+'.csv'
with open(join(logs_folder, file_name), 'w') as fp:
writer = csv.writer(fp, delimiter = "\n")
writer.writerow(list_input)

Try using

import datetime
from os.path import dirname, abspath, join, exists
logs_folder = join(dirname(dirname(abspath(__file__))), 'logs')
file_name = datetime.datetime.now().strftime("%Y-%m-%d %H_%M_%S")+'.csv'
with open(join(logs_folder, file_name), 'w') as fp:
writer = csv.writer(fp, delimiter = "\n")
writer.writerow(list_input)

Python os.path.join on Windows

Windows has a concept of current directory for each drive. Because of that, "c:sourcedir" means "sourcedir" inside the current C: directory, and you'll need to specify an absolute directory.

Any of these should work and give the same result, but I don't have a Windows VM fired up at the moment to double check:

"c:/sourcedir"
os.path.join("/", "c:", "sourcedir")
os.path.join("c:/", "sourcedir")


Related Topics



Leave a reply



Submit