257

I have written a code in python which uses / to make a particular file in a folder, if I want to use the code in windows it will not work, is there a way by which I can use the code in Windows and Linux.

In python I am using this code:

pathfile=os.path.dirname(templateFile)
rootTree.write(''+pathfile+'/output/log.txt')

When I will use my code in suppose windows machine my code will not work.

How do I use "/" (directory separator) in both Linux and Windows?

jww
  • 97,681
  • 90
  • 411
  • 885
hulk007
  • 2,751
  • 2
  • 13
  • 10
  • 1
    You can define it in the beginning depending on Win/*nix and then work with the variable. – fedorqui Apr 15 '13 at 08:43
  • 13
    In Windows you can use either \ or / as a directory separator. – SecurityMatt Apr 15 '13 at 08:43
  • 14
    Windows supports `/` in directory paths. What specific problem are you having? Post some code that illustrates the problem. – Michael Geary Apr 15 '13 at 08:44
  • Unless you depend on Windows userspace programs, forward slash works as well as backward. Some cmd commands have problems with that however. – Pihhan Apr 15 '13 at 08:46
  • @MichaelGeary: I have edited the question with example, Can you have a look now? – hulk007 Apr 15 '13 at 08:47
  • 1
    @MichaelGeary: Only sometimes. Sometimes it doesn't. (Only saying it from experience -- I don't know exactly in which situations it fails and in which it doesn't.) – user541686 Apr 15 '13 at 08:50
  • 1
    @Mehrdad: Do you know an example for which the Win32 API doesn't accept '/'? (not counting cmd.exe and other programs) – Eryk Sun Apr 15 '13 at 08:54
  • 1
    @eryksun: Sure; just try `PathCombine(buf, "C:/", "Temp")` and then try `PathCombine(buf, "C:\\", "Temp")`, for example. Although I'm not sure why you're discounting cmd.exe, it's kind of crucial for implementing `system()` in various languages... – user541686 Apr 15 '13 at 09:00
  • @Mehrdad: `"C:/\Temp"` may be ugly, but it is a valid path. The slash or backslash can be repeated. – Eryk Sun Apr 15 '13 at 09:25
  • @eryksun: Picky, picky, are we? :) How about `PathIsRoot("C:\\") == TRUE` and `PathIsRoot("C:/") == FALSE` then? (FYI, I don't even have these memorized. I'm just trying them out right now because you asked for an example. It's easy enough to make your own, just play around with the functions.) – user541686 Apr 15 '13 at 09:28
  • Have you tried `os.path.sep`? – Zeinab Abbasimazar Sep 17 '17 at 07:28
  • 1
    Windows does not support unix style slash in explicit relative path of executable, i.e. e.g. `./script.py` does not work on Windows, but `.\script.py` does. Just try in cmd.exe. – Velda May 03 '18 at 15:40

11 Answers11

330

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"))

Serban Razvan
  • 4,250
  • 3
  • 21
  • 22
166

Use:

import os
print os.sep

to see how separator looks on a current OS.
In your code you can use:

import os
path = os.path.join('folder_name', 'file_name')
Alexander Kononenko
  • 1,952
  • 1
  • 10
  • 17
93

You can use os.sep:

>>> import os
>>> os.sep
'/'
Adem Öztaş
  • 20,457
  • 4
  • 34
  • 42
72

os.path.normpath(pathname) should also be mentioned as it converts / path separators into \ separators on Windows. It also collapses redundant uplevel references... i.e., A/B and A/foo/../B and A/./B all become A/B. And if you are Windows, these all become A\B.

David Ferenczy Rogožan
  • 23,966
  • 9
  • 79
  • 68
Jon Rosen
  • 729
  • 5
  • 2
  • 7
    This is IMO the best answer to the question as it was phrased, "how to use “/” (directory separator) in both Linux and Windows". And it's also eminently useful -- I'd much rather do `os.path.normpath('a/b/c/d/file.ext')` than `os.path.join('a','b','c','d','file.ext')` when I need to specify a long path. – ukrutt Aug 17 '16 at 15:26
  • I also found this answer to be very helpful. I was looking for a method for generating paths with a consistent separator. The famous `os.path.join` just joins anything provided. e.g. `join("a/b", "c\d")` gives `a/b\c\d` (on windows). But i can get the expected result with the proper combination of `join` and `normpath`, e.g. `a\b\c\d` (on windows) – Anubis Apr 05 '18 at 14:06
  • I use this import: `from os.path import normpath as normpath # Given a Windows or Linux path, fixes path separators to match the current OS.` then I can use something like `normpath("a/b/c/d/e/f")` which seems cleaner than any alternative. – Contango Jun 28 '21 at 10:37
36

If you are fortunate enough to be running Python 3.4+, you can use pathlib:

from pathlib import Path

path = Path(dir, subdir, filename)  # returns a path of the system's path flavour

or, equivalently,

path = Path(dir) / subdir / filename
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
  • 5
    It's 2020, so **this should now be the accepted answer**. The Python devs added it to overcome problems in `os`, and it makes everything easier. Ex `path.read_text(encoding="utf8")`, `path.read_bytes()`, `path.resolve()`, `path.unlink()`, ... – Douglas Myers-Turnbull Sep 22 '20 at 20:06
20

Some useful links that will help you:

Maroun
  • 94,125
  • 30
  • 188
  • 241
13

Do a import os and then use os.sep

JackPoint
  • 4,031
  • 1
  • 30
  • 42
11

You can use "os.sep "

 import os
 pathfile=os.path.dirname(templateFile)
 directory = str(pathfile)+os.sep+'output'+os.sep+'log.txt'
 rootTree.write(directory)
P113305A009D8M
  • 344
  • 1
  • 4
  • 13
5

Don't build directory and file names your self, use python's included libraries.

In this case the relevant one is os.path. Especially join which creates a new pathname from a directory and a file name or directory and split that gets the filename from a full path.

Your example would be

pathfile=os.path.dirname(templateFile)
p = os.path.join(pathfile, 'output')
p = os.path.join( p, 'log.txt')
rootTree.write(p)
mmmmmm
  • 32,227
  • 27
  • 88
  • 117
5

If someone is looking for something like this:

He/she wants to know the parent directory and then go to the sub-folders and maybe than to a specific file. If so, I use the following approach.

  1. I am using python 3.9 as of now. So in that version, we have the os module for handling such tasks. So, for getting the parent directory:
parent_dir = os.path.pardir
  1. It's a good coding practice to not hardcode the file path separators (/ or \). Instead, use the operating system dependant mechanism provided by the above-mentioned os module. It makes your code very much reusable for other purposes/people. It goes like this (just an example) :

path = os.path.pardir + os.sep + 'utils' + os.sep + 'properties.ini'

print(f'The path to my global properties file is :: {path}')

Output:

..\utils\properties.ini

You can surely look at the whole documentation here : https://docs.python.org/3/library/os.html

mr-possible
  • 109
  • 1
  • 9
0

I use pathlib for most things, so I like: pathlib.os.sep.

Usually pathlib is the better choice if you don't need os!

LC117
  • 426
  • 4
  • 12