If you prefer to hard-code the directory separator character, you should use the forward slash ( / ) character. It is the only recognized directory separator character on Unix systems, as the output from the example shows, and is the AltDirectorySeparatorChar on Windows.
On Windows, paths are written using backslashes (\) as the separator between folder names. OS X and Linux, however, use the forward slash (/) as their path separator. If you want your programs to work on all operating systems, you will have to write your Python scripts to handle both cases.
split() method in Python is used to Split the path name into a pair head and tail. Here, tail is the last path name component and head is everything leading up to that. In the above example 'file. txt' component of path name is tail and '/home/User/Desktop/' is head.
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"))
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')
You can use os.sep:
>>> import os
>>> os.sep
'/'
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
.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With