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
Windows path to Python path
Python - handling windows path with '\' characters
How to convert Windows path to WSL path?
Python 3 Quick Tip: The easy way to deal with file paths on Windows, Mac and Linux
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
Rather than hardcoding paths in your Python script we should make use of the path operation from the module os.
os.path.expanduser(path) expands the path to the user's home directory
os.path.join(path1,*path2*,...) joins path elements with the appropriate separator
os.sep gives the OS dependent path separator (/ for Linux/Unix, \ for Windows)
os.getcwd() gives the current working directory
os.path.abspath(path) gives the OS dependent absolute path of a given path
Example:
>>>import os
>>>path = os.path.join(os.path.expanduser('~'), 'documents', 'python', 'file.txt')
>>>print (path)
Result
/home/user/documents/python/file.txt ## when on Ubuntu
C:\Users\user\documents\python\file.txt ## when running Windows
I don't have permission to add comments...so I will just try to answer.
The path at UNIX will be like: /home/user/file.txt
When you at any folder and want to get the absolute path of a file, you could use the readlink command:
readlink -f file.txt
example at our server:
$ readlink -f format.log
/home/dli/format.log