pathlib is an OO library, not a communication protocol. Just send strings.
Windows can handle paths with forward slashes just fine, and both pathlib and os.path can normalise such paths for you. You probably want to normalise paths in your protocol to use POSIX path separators (forward slashes).
You can convert relative Windows paths to POSIX paths using pathlib.PurePosixPath(), for example:
>>> from pathlib import Path, PurePosixPath
>>> Path('relative\path\on\windows')
WindowsPath('relative\path\on\windows')
>>> PurePosixPath(_)
PurePosixPath('relative/path/on/windows')
>>> str(_)
'relative/path/on/windows'
If your server receives a relative paths using Windows conventions, use PureWindowsPath() to convert it to a pathlib object, then pass that to Path() to convert:
>>> from pathlib import Path, PureWindowsPath
>>> received = 'relative\path\on\windows'
>>> PureWindowsPath(received)
PureWindowsPath('relative/path/on/windows')
>>> Path(_)
PosixPath('relative/path/on/windows')
If you keep paths as strings, then you can use str.replace(os.altsep, os.sep) to achieve the same on the Windows side before sending:
>>> import os
>>> p = 'relative\path\on\windows'
>>> p.replace(os.altsep, os.sep)
'relative/path/on/windows'
and you can always just use relative_path.replace('\\', os.sep) to force the issue.
I have been searching the web for a solution without a result.
I made this small script that can be used. Feel free to use it.
I wonder is there a better solution on the issue to convert windows path to python path?
"""
A path, in Windows "C:\Folder" . in Python it is "C:/Folder".
In Python the "\" character can get interpreted as the ESCAPE character.
When an 'r' or 'R' prefix is present, a character following a backslash is
included in the string without change, and all backslashes are left in the string.
"""
def main():
# - YOUR INPUT - IMPORTANT: keep the r in front of path string here.
win_path = r"<TYPE YOUR PATH HERE>"
# Call function to convert from windows to Python path.
path_py = py_path(win_path)
print("Your Python Path: ", path_py)
def py_path(win_path):
python_path = "" # The result of this script.
# Convert to ASCII list
ascii_values_list = []
for character in win_path:
ascii_values_list.append(ord(character))
# Replace all ASCII values for "\" (=92) with value for "/" (=47).
for i in range(0, len(ascii_values_list)):
if ascii_values_list[i] == 92:
ascii_values_list[i] = 47
path_py = "" # Convert ASCII list to string
for val in ascii_values_list:
path_py = path_py + chr(val)
if path_py[-1] != "/": # Add "/" at end of path if needed.
path_py = path_py + "/"
return path_py
if __name__ == "__main__":
main() # Script goes there.
# EOF
pathlib is an OO library, not a communication protocol. Just send strings.
Windows can handle paths with forward slashes just fine, and both pathlib and os.path can normalise such paths for you. You probably want to normalise paths in your protocol to use POSIX path separators (forward slashes).
You can convert relative Windows paths to POSIX paths using pathlib.PurePosixPath(), for example:
>>> from pathlib import Path, PurePosixPath
>>> Path('relative\path\on\windows')
WindowsPath('relative\path\on\windows')
>>> PurePosixPath(_)
PurePosixPath('relative/path/on/windows')
>>> str(_)
'relative/path/on/windows'
If your server receives a relative paths using Windows conventions, use PureWindowsPath() to convert it to a pathlib object, then pass that to Path() to convert:
>>> from pathlib import Path, PureWindowsPath
>>> received = 'relative\path\on\windows'
>>> PureWindowsPath(received)
PureWindowsPath('relative/path/on/windows')
>>> Path(_)
PosixPath('relative/path/on/windows')
If you keep paths as strings, then you can use str.replace(os.altsep, os.sep) to achieve the same on the Windows side before sending:
>>> import os
>>> p = 'relative\path\on\windows'
>>> p.replace(os.altsep, os.sep)
'relative/path/on/windows'
and you can always just use relative_path.replace('\\', os.sep) to force the issue.
.as_posix() is way forward.
from pathlib import Path
p = Path('./my_dir/my_file.txt')
print(p)
# my_dir\my_file.txt
print(p.as_posix())
# my_dir/my_file.txt
Using absolute unix paths in windows with python - Stack Overflow
Normalizing Path between Windows and macOS/Linux
linux - Python script for changing windows path to unix path - Stack Overflow
Windows Path 2 Python Path
If you are running your code on a *nix machine, you can use the PureWindowsPath class:
>>> from pathlib import PureWindowsPath, PurePosixPath
>>> path = PureWindowsPath('C:\\Users\\foo\\bar')
>>> path.parts
('c:\\', 'Users', 'foo', 'bar')
>>> PurePosixPath('/usr', *path.parts[2:])
PurePosixPath('/usr/foo/bar')
You can apply the string replace method to every line in a text file as follows:
with open("input.csv", "r") as f_in:
with open("output.csv", "w") as f_out:
for line in f_in:
new_line = line.replace(...) # magic goes here
f_out.write("{}\n".format(new_line))
I'm a little late to this party, but I found the following approach to work well:
from pathlib import Path, PureWindowsPath
class AgnosticPath(Path):
"""A class that can handle input with Windows (\\) and/or posix (/) separators for paths"""
def __new__(cls, *args, **kwargs):
new_path = PureWindowsPath(*args).parts
if (os.name != "nt") and (len(new_path) > 0) and (new_path[0] in ("/", "\\")):
new_path = ("/", *new_path[1:])
return super().__new__(Path, *new_path, **kwargs)
To seamlessly apply this to existing code, save it to a separate file and replace from pathlib import Path with from <myfile> import AgnosticPath as Path
» pip install wsl-path-converter
Use os.path.abspath(), and also os.path.expanduser() for files relative to the user's home directory:
print os.path.abspath("/var/lib/blob_files/myfile.blob")
>>> C:\var\lib\blob_files\myfile.blob
print os.path.abspath(os.path.expanduser("~/blob_files/myfile.blob"))
>>> C:\Users\jerry\blob_files\myfile.blob
These will "do the right thing" for both Windows and POSIX paths.
expanduser() won't change the path if it doesn't have a ~ in it, so you can safely use it with all paths. Thus, you can easily write a wrapper function:
import os
def fixpath(path):
return os.path.abspath(os.path.expanduser(path))
Note that the drive letter used will be the drive specified by the current working directory of the Python process, usually the directory your script is in (if launching from Windows Explorer, and assuming your script doesn't change it). If you want to force it to always be C: you can do something like this:
import os
def fixpath(path):
path = os.path.normpath(os.path.expanduser(path))
if path.startswith("\\"): return "C:" + path
return path
Ok, I got an answer by myself.
os.path.exists(os.path.abspath(filePath))
Maybe it will be useful for anybody
I'm having a bit of difficulty normalizing the between the OS while using the pathlib library. So far, this is what I have when converting a Windows path to macOS/Linux:
from pathlib import Path directory = "C:\\some1\\some2\\some3\\some4" directory_1 = Path(directory).resolve() # "/some1/some2/C:\some1\some2\some3\some4 directory_2 = os.path.normpath(directory) # "/some1/some2/C:\some1\some2\some3\some4
Is there a cleaner way of doing this? I've tried multiple ways than even the ones stated above, but it seems fairly difficult other than doing replace('\\', '/'), and even that line of code can be wrong due to the anchor still existing. Any suggestions?
Unless you're using a really early version of Windows: "/blah/whatever/" just works for your OP.
#!/usr/bin/python
#! python3
#! python2
# -*- coding: utf-8 -*-
"""win2ubu.py changes WINFILEPATH Printing UBUNTU_FILEPATH
Author: Joe Dorocak aka Joe Codeswell (JoeCodeswell.com)
Usage: win2ubu.py WINFILEPATH
Example: win2ubu.py "C:\\1d\ProgressiveWebAppPjs\\Polymer2.0Pjs\\PolymerRedux\\zetc\\polymer-redux-polymer-2"
prints /mnt/c/1d/ProgressiveWebAppPjs/Polymer2.0Pjs/PolymerRedux/zetc/polymer-redux-polymer-2
N.B. spaceless path needs quotes in BASH on Windows but NOT in Windows DOS prompt!
"""
import sys,os
def winPath2ubuPath(winpath):
# d,p = os.path.splitdrive(winpath) # NG only works on windows!
d,p = winpath.split(':')
ubupath = '/mnt/'+d.lower()+p.replace('\\','/')
print (ubupath)
return ubupath
NUM_ARGS = 1
def main():
args = sys.argv[1:]
if len(args) != NUM_ARGS or "-h" in args or "--help" in args:
print (__doc__)
sys.exit(2)
winPath2ubuPath(args[0])
if __name__ == '__main__':
main()
I have been searching the web for a solution without a result.
I made this small script that can be used. Feel free to use it.
I wonder is there a better solution on the issue to convert windows path to python path?
"""
A path, in Windows "C:\Folder" . in Python it is "C:/Folder".
In Python the "\" character can get interpreted as the ESCAPE character.
When an 'r' or 'R' prefix is present, a character following a backslash is
included in the string without change, and all backslashes are left in the string.
"""
def main():
# - YOUR INPUT - IMPORTANT: keep the r in front of path string here.
win_path = r"<TYPE YOUR PATH HERE>"
# Call function to convert from windows to Python path.
path_py = py_path(win_path)
print("Your Python Path: ", path_py)
def py_path(win_path):
python_path = "" # The result of this script.
# Convert to ASCII list
ascii_values_list = []
for character in win_path:
ascii_values_list.append(ord(character))
# Replace all ASCII values for "\" (=92) with value for "/" (=47).
for i in range(0, len(ascii_values_list)):
if ascii_values_list[i] == 92:
ascii_values_list[i] = 47
path_py = "" # Convert ASCII list to string
for val in ascii_values_list:
path_py = path_py + chr(val)
if path_py[-1] != "/": # Add "/" at end of path if needed.
path_py = path_py + "/"
return path_py
if __name__ == "__main__":
main() # Script goes there.
# EOF
You can use os.path.abspath() to convert it:
print(os.path.abspath("P:\python\t\temp.txt"))
>>> P:/python/t/temp.txt
See the documentation of os.path here.
I've solved it.
The issues lies with the python interpreter. \t and all the others don't exist as such data, but are interpretations of nonprint characters.
So I got a bit lucky and someone else already faced the same problem and solved it with a hard brute-force method:
http://code.activestate.com/recipes/65211/
I just had to find it.
After that I have a raw string without escaped characters, and just need to run the simple replace() on it to get a workable path.
pathlib has an as_posix method to convert from Windows to POSIX paths:
pathlib.path(r'foo\bar').as_posix()
Apart from this, you can generally construct system-specific paths by calling the appropriate constructor. The documentation states that
You cannot instantiate a
WindowsPathwhen running on Unix, but you can instantiatePureWindowsPath. [or vice versa]
So use the Pure* class constructor:
str(pathlib.PurePosixPath(your_posix_path))
However, this won’t do what you want if your_posix_path contains backslashes, since \ (= Windows path separator) is just a regular character as far as POSIX is concerned. So a\b is valid POSIX filename, not a path denoting a file b inside a directory b, and PurePosixPath will preserve this interpretation:
>>> str(pathlib.PurePosixPath(r'a\b'))
'a\\b'
To convert Windows to POSIX paths, use the PureWindowsPath class and convert via as_posix:
>>> pathlib.PureWindowsPath(r'a\b').as_posix()
'a/b'
Python pathlib if you want to manipulate Windows paths on a Unix machine (or vice versa) - you cannot instantiate a WindowsPath when running on Unix, but you can instantiate PureWindowsPath/PurePosixPath
.

You can keep it simple by simply by converting it to a "raw" string. This can be used anywhere any other path can be used. (os.path, Pathlib, etc.)
mypath = r'C:\Users\user.name\new_project\data' print( 'mypath is =', mypath )
Output: path is = C:\Users\user.name\new_project\data
I solved this problem by using .encode('unicode escape')
for example:
from pathlib import Path
def input_to_path():
user_input = input('Please copy and paste the folder address')
user_input.encode('unicode escape')
p = Path(user_input)
return(p)