Convert WindowsPath to PosixPath
I am using pathlib to manage my paths in my Python project using the Path class. When I am using Linux, everything works fine. But on Windows, I have a little issue. At some point in my code, I have to write a JavaScript file which lists the references to several other files. These paths have to be written in POSIX format. But when I do str(my_path_instance) on Windows, The path is written in Windows format. Do you know a simple way to convert a WindowsPath to a PosixPath with pathlib ?
2 Answers 2
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 WindowsPath when running on Unix, but you can instantiate PureWindowsPath . [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 script for changing windows path to unix path
I want a script where I can paste a windows path as argument, and then the script converts the path to unix path and open the path using nautilus. I want to be able to use the script as follows:
mypythonscript.py \\thewindowspath\subpath\
import sys, os path = "nautilus smb:"+sys.argv[1] path = path.replace("\\","/") os.system(path)
mypythonscript.py '\\thewindowspath\subpath\'
mypythonscript.py \\thewindowspath\subpath\
EDIT: I think I have to add that the problem is that without ‘ the \ in the argument is treated as escape character. The solution does not necessarily have to be a python script but I want (in Linux) to be able to just paste a windows path as argument to a script.
What is the source for the strings? You could create a simple GUI to avoid escaping and/or investigate drag-n-drop on a script icon/applet solution.
The strings with the windows path I receive in emails. Maybe I have to create a GUI app for this as you suggest. But I just think that this should be a quite common problem.
Since I see you have multiple language tags, if you’re just looking for a solution that works, there’s winepath. I expect it’s probably more robust than any script you can slap together in a few minutes, if you happen to have wine available.
5 Answers 5
Unless you’re using a really early version of Windows: «/blah/whatever/» just works for your OP.
The windows path is in the format using \ (received in various emails) I just want to be able to copy and paste as argument to the script.
#!/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()
Actually I had something like this a while ago, I made a bash script to automatically download links I copy into clipboard, here it is edited to use your program (you first need to install xclip if you don’t already have it):
#!/bin/bash old="" new="" old="$(xclip -out -selection c)" while true do new="$(xclip -out -selection c)" if [ "$new" != "$old" ] then old="$new" echo Found: $new mypythonscript.py $new fi sleep 1 done exit 0
Now whenever you copy something new into the clipboard, your Python script will be executed with an argument of whatever is in your clipboard.
Преобразование пути Windows в Linux в Python
Как разработчик, обычно приходится работать с несколькими операционными системами, однако каждая операционная система имеет свой собственный формат пути к файлу, который иногда может вызывать проблемы.
Поэтому важно преобразовать их в путь, подходящий для их операционной системы. В этой статье вы точно увидите, как преобразовать путь Windows, путь linux в python.
Путь Windows
C:\Users\JohnDoe\Documents\example.txt
Путь к Linux
C:/Users/Username/Documents/file.txt
Выше приведены примеры того, как пути Windows и Linux, как вы можете видеть, используют разные обратные косые черты, поэтому давайте посмотрим, как их преобразовать.
Преобразование пути Windows в Linux в Python с использованием модуля Pathlib
from pathlib import Path windows_path = r'C:\Users\JohnDoe\Documents\example.txt' linux_path = Path(windows_path).as_posix() print(linux_path)
Как видите, это всего 3 строки кода, потому что мы использовали модуль pathlib для преобразования пути Windows в Linux в Python. После запуска этой программы вы увидите, что она печатает путь в формате Linux, как показано ниже.
C:/Users/Username/Documents/file.txt
Как видите, мы успешно преобразовали путь Windows в путь Linux в Python. Я надеюсь, что вы нашли это руководство полезным и полезным, поделитесь им с кем-нибудь, кому оно может быть полезным.
Спасибо за прочтение, хорошего дня 🙂
Converting Windows Path to Linux
I created a CSV file ( driving_log.csv ) for the filepath of each image that my simulator created but I was using my brother’s Windows computer when I did that so now the file path looks like this for each image (and there is almost 14000 of them). I get an error when invoking it from my file.py , which is in the same directory as the CSV file.
C:\Users\a-ozb\Desktop\onur\behavirol-cloning-carla\IMG\center_2020_02_08_14_16_38_988.jpg,C:\Users\a-ozb\Desktop\onur\behavirol-cloning-carla\IMG\left_2020_02_08_14_16_38_988.jpg,C:\Users\a-ozb\Desktop\onur\behavirol-cloning-carla\IMG\right_2020_02_08_14_16_38_988.jpg,0,0,0,7.918889E-06
/home/onur/Documents/behavioral-cloning-CARLA/IMG/center_2020_02_08_14_16_38_988.jpg,left_2020_02_08_14_16_38_988.jpg,right_2020_02_08_14_16_38_988.jpg,0,0,0,7.918889E-06
As you can see, I need everything that comes after \IMG\ . What is the best way to go about this? Should I just slice each string at IMG\ and take what’s after it or use regex? I’ve tried this for this specific line to see if it works but it doesn’t:
string = r"C:\Users\a-ozb\Desktop\onur\behavirol-cloning-carla\IMG\center_2020_02_08_14_16_38_988.jpg,C:\Users\a-ozb\Desktop\onur\behavirol-cloning-carla\IMG\left_2020_02_08_14_16_38_988.jpg,C:\Users\a-ozb\Desktop\onur\behavirol-cloning-carla\IMG\right_2020_02_08_14_16_38_988.jpg,0,0,0,7.918889E-06 " new_string = string.replace(r"'C:\Users\a-ozb\Desktop\onur\behavirol-cloning-carla\IMG\'", r"'/home/onur/Documents/behavioral-cloning-CARLA/IMG/'", 3) print(new_string)
C:\Users\a-ozb\Desktop\onur\behavirol-cloning-carla\IMG\center_2020_02_08_14_16_38_988.jpg,C:\Users\a-ozb\Desktop\onur\behavirol-cloning-carla\IMG\left_2020_02_08_14_16_38_988.jpg,C:\Users\a-ozb\Desktop\onur\behavirol-cloning-carla\IMG\right_2020_02_08_14_16_38_988.jpg,0,0,0,7.918889E-06