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))
Answer from Selcuk on Stack OverflowIf 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
Using absolute unix paths in windows with python - Stack Overflow
Windows path to Python path
python - How do I normalize a path format to Unix-style while on Windows? - Stack Overflow
Convert Unix path to Windows path in a custom function?
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()
» 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 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 convert Windows-style path to UNIX-style after calling os.path.normpath. The conversion can be conveniently done with pathlib.PureWindowsPath.as_posix:
import os.path
from pathlib import PureWindowsPath
path = r'\foo\\bar'
path = os.path.normpath(path)
if os.path.sep == '\\':
path = PureWindowsPath(path).as_posix()
print(path)
This outputs, in Windows:
/foo/bar
There are four cases to handle, all of which should output a normalized Posix path:
- Windows path on Posix system
- Posix path on Posix system
- Windows path on Windows system
- Posix path on Windows system
The other answer is close but doesn't handle all of these. This does:
from os.path import normpath
from pathlib import PureWindowsPath
def convert(path):
return PureWindowsPath(normpath(PureWindowsPath(path).as_posix())).as_posix()
print('Windows path: ' + convert(r'.\path\to\..\to\file'))
print('Posix path: ' + convert('./path/to/../to/file'))
which will output the following on both Windows and Posix systems:
Windows path: path/to/file
Posix path: path/to/file
Two nested PureWindowsPath instances are necessary to handle case 1, Windows path on a Posix system. If you don't care about that case and only need to handle the other three cases, a single nested call is sufficient:
def convert(path):
return PureWindowsPath(normpath(path)).as_posix()
Since normpath is able to normalize Posix paths on Windows, but normath does not normalize Windows paths on Posix systems.
Windows Build 17046 [1] contains new wslpath utility that can translate paths from/to WSL/Windows. This was known missing WSL feature. [2]
Example usage:
$ echo $0
/bin/bash
$ which wslpath
/bin/wslpath
$ wslpath -a 'C:\\aaa\\bbb\\ccc\\foo.zip'
/mnt/c/aaa/bbb/ccc/foo.zip
You can call wslpath from Powershell on Windows:
>>> wsl wslpath -a 'C:\\aaa\\bbb\\ccc\\foo.zip'
/mnt/c/aaa/bbb/ccc/foo.zip
wslpath options and parameters:
-a force result to absolute path format
-u translate from a Windows path to a WSL path (default)
-w translate from a WSL path to a Windows path
-m translate from a WSL path to a Windows path, with ‘/’ instead of ‘\\’
Edit (05/24)
If you need the opposite conversion, i.e. to get a path suitable for WSL in PowerShell, you can use:
$pathInWSL = wsl wslpath -a -u "$(Get-Location)\foo.txt".Replace('\', '\\')
# "$(Get-Location)\foo.txt".Replace('\', '\\') = C:\\bar\\baz\\foo.txt
# $pathInWSL = /mnt/c/bar/baz/foo.txt
wsl cat $pathInWSL
# content of /mnt/c/bar/baz/foo.txt
I wrote a bat file to do this. Just place the file wherever you are working or add it to your path (or just put it above your code, which would be easier to work with). Remember to assign "variable" to your file path first (if you are using a separate file, try using parameters).
What the code does:
1) Get the first letter of the path, which is the drive.
2) Remove the first two letters.
3) Change the slashes.
4) This is the tricky part: since Linux is case sensitive, we need to convert uppercase drive letter to lowercase. Do this by matching each (tell me if there is a better way). You can remove unnecessary drive letters too, since you probably have no more than ten drives.
5) Combine everything to give the final string.
The result:
Input:
E:\myfiles\app1\data\file.csv
Output (with the quotation marks):
"/mnt/e/myfiles/app1/data/file.csv"
The code is as follows:
@echo OFF
set "variable=E:\myfiles\app1\data\file.csv"
set "drive=%variable:~0,1%"
set variable=%variable:~2%
set "variable=%variable:\=/%"
if %drive%==A set "drive=a"
if %drive%==B set "drive=b"
if %drive%==C set "drive=c"
if %drive%==D set "drive=d"
if %drive%==E set "drive=e"
if %drive%==F set "drive=f"
if %drive%==G set "drive=g"
if %drive%==H set "drive=h"
if %drive%==I set "drive=i"
if %drive%==J set "drive=j"
if %drive%==K set "drive=k"
if %drive%==L set "drive=l"
if %drive%==M set "drive=m"
if %drive%==N set "drive=n"
if %drive%==O set "drive=o"
if %drive%==P set "drive=p"
if %drive%==Q set "drive=q"
if %drive%==R set "drive=r"
if %drive%==S set "drive=s"
if %drive%==T set "drive=t"
if %drive%==U set "drive=u"
if %drive%==V set "drive=v"
if %drive%==W set "drive=w"
if %drive%==X set "drive=x"
if %drive%==Y set "drive=y"
if %drive%==Z set "drive=z"
set "variable=/mnt/%drive%%variable%"
echo "%variable%"
@echo ON