[python] How to use "/" (directory separator) in both Linux and Windows in Python?

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?

This question is related to python linux windows unix

The answer is


You can use os.sep:

>>> import os
>>> os.sep
'/'

Do a import os and then use os.sep


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

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)

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

Some useful links that will help you:


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)

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.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to linux

grep's at sign caught as whitespace How to prevent Google Colab from disconnecting? "E: Unable to locate package python-pip" on Ubuntu 18.04 How to upgrade Python version to 3.7? Install Qt on Ubuntu Get first line of a shell command's output Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running? Run bash command on jenkins pipeline How to uninstall an older PHP version from centOS7 How to update-alternatives to Python 3 without breaking apt?

Examples related to windows

"Permission Denied" trying to run Python on Windows 10 A fatal error occurred while creating a TLS client credential. The internal error state is 10013 How to install OpenJDK 11 on Windows? I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? git clone: Authentication failed for <URL> How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning" XCOPY: Overwrite all without prompt in BATCH Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory how to open Jupyter notebook in chrome on windows Tensorflow import error: No module named 'tensorflow'

Examples related to unix

Docker CE on RHEL - Requires: container-selinux >= 2.9 What does `set -x` do? How to find files modified in last x minutes (find -mmin does not work as expected) sudo: npm: command not found How to sort a file in-place How to read a .properties file which contains keys that have a period character using Shell script gpg decryption fails with no secret key error Loop through a comma-separated shell variable Best way to find os name and version in Unix/Linux platform Resource u'tokenizers/punkt/english.pickle' not found