Python windows path to linux 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\

The script currently looks like this:

import sys, os

path = "nautilus smb:"+sys.argv[1]

path = path.replace("\\","/")

os.system(path)

I almost works :)
The problem is that I have to add ‘ around the argument… like this:

mypythonscript.py '\\thewindowspath\subpath\'

Anyone who knows how I can write a script that allows that argument is without ‘ , … i.e. like this:

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.

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\

The script currently looks like this:

import sys, os

path = "nautilus smb:"+sys.argv[1]

path = path.replace("\\","/")

os.system(path)

I almost works :)
The problem is that I have to add ‘ around the argument… like this:

mypythonscript.py '\\thewindowspath\subpath\'

Anyone who knows how I can write a script that allows that argument is without ‘ , … i.e. like this:

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.

As a developer, it’s common to work on multiple operating systems, However, each operating system has its own file path format, which can sometimes cause problems.

So it is important to convert them to their operating system suitable path, In this article you are exactly going to see how to convert windows path linux path in python.

Windows Path


C:\Users\JohnDoe\Documents\example.txt

Linux Path


C:/Users/Username/Documents/file.txt

Above are the examples of how windows and linux path as you can see it uses different backslashes so let’s see how to convert them.

Converting Windows Path To Linux In Python Using Pathlib Module


from pathlib import Path

windows_path = r'C:\Users\JohnDoe\Documents\example.txt'
linux_path = Path(windows_path).as_posix()

print(linux_path)

As you can see it just 3 lines of code because we used pathlib module to convert windows path to linux, After running this program you will see it printing the path in linux format like below


C:/Users/Username/Documents/file.txt

As you can see we successfully converted windows path to linux path using python, I hope you found this tutorial helpful and useful do share it with someone who might find it helpful.

Thanks for reading, Have a nice day 🙂

Преобразование пути 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. Я надеюсь, что вы нашли это руководство полезным и полезным, поделитесь им с кем-нибудь, кому оно может быть полезным.

Спасибо за прочтение, хорошего дня 🙂

Ссылка на источник

  •  
  • linux

  • python

  • escaping

  • bash

  •  18-06-2021
  •  | 
  •  

Question

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\

The script currently looks like this:

import sys, os

path = "nautilus smb:"+sys.argv[1]

path = path.replace("\\","/")

os.system(path)

I almost works :)
The problem is that I have to add ‘ around the argument… like this:

mypythonscript.py '\\thewindowspath\subpath\'

Anyone who knows how I can write a script that allows that argument is without ‘ , … i.e. like this:

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.

OTHER TIPS

Unless you’re using a really early version of Windows: «/blah/whatever/» just works for your OP.

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.

To avoid dealing with escapes in the shell you could work with the clipboard directly:

import os
try:
    from Tkinter import Tk
except ImportError:
    from tkinter import Tk # py3k

# get path from clipboard
path = Tk().selection_get(selection='CLIPBOARD')

# convert path and open it
cmd = 'nautilus'
os.execlp(cmd, cmd, 'smb:' + path.replace('\\', '/'))

ntpath, urlparse, os.path modules might help to handle the paths more robustly.

#!/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()

may want to try

my_argv_path = " ".join(sys.argv[1:])

as the only reason it would split the path into separate args is spaces in pasted path

(eg: C:\Program Files would end up as two args ["c:\Program","Files"])

  • Python portable скачать для windows
  • Python в системном администрировании windows
  • Python pip как пользоваться windows
  • Python работа с буфером обмена windows
  • Python активация виртуального окружения windows