-1

Is there any way to copy a path on Windows that already comes without the inverted slashes"" and come with the normal one "/" so that I don't need everytime to change 1 by 1 ?

If there isn't, is there some way to make python understDand the inverted slashes inside the string?

Path copied right from the Address bar:

print("C:\Users\USER\Documents")

Path that I intend to get:

print("C:/Users/USER/Documents")

Or even with this double slashes:

print("C:\\Users\\USER\\Documents")
Henrique
  • 11
  • 1
  • 1
    can you clarify where do you want to copy the file path from (eg file explorer)? The best way to handle file paths in python is through `pathlib` which handles both windows and linux file path including the file name separator – user7440787 Nov 23 '20 at 08:32
  • Gonna look up that lib, thanks! But yes, I intended to copy from file explorer. – Henrique Nov 23 '20 at 21:04

4 Answers4

2

You just need to handle the conversion from str to repr:

>>> a = r'C:\Users\USER\Documents'
>>> print(a)
C:\Users\USER\Documents
>>> b = '%r' %a
>>> print(b)
'C:\\Users\\USER\\Documents'

Please keep in mind that a and b are not exactly the same thing but they both print as string. See interesting explanation.

However, if you need to use that filename as a variable, the best way is to use either os.path or pathlib which are both part of python's standard library, see here.

You can simply pass the filename you get from file explorer as a string:

from pathlib import Path
filename = Path(r"C:\Users\USER\Documents")

If you then want to get the path with double backslashes, you can use the filename representation (repr):

>>> b = "%r" % filename.name
>>> print(b)
'C:\\Users\\USER\\Documents'
user7440787
  • 831
  • 7
  • 22
1

The path that you intend to get (C:/Users/USER/Documents) is not supported by Windows. It is used in MacOS or Linux, as I far as I know.

Guseyn013
  • 63
  • 9
0

Best format to work in windows is using// instead of / :

print("C:\user\USER\Documents".replace('\', '\\')

Ahmed
  • 796
  • 1
  • 5
  • 16
-1

By brackets and inverted brackets do you mean slashes? If you want to get a path from the form "C:\Users\USER\Documents" to "C:/Users/USER/Documents", I would just use the str.replace method. As in "C:\Users\USER\Documents".replace("\\", "/")

Ben
  • 82
  • 11
  • Yes, I meant slashes, already eddited. I'm new in programming so I didn't know this .replace() function. Thanks! – Henrique Nov 23 '20 at 21:00
  • it's not the best way to deal with filenames. It is recommended to use either `os.path` of `pathlib`. Also, you could have asked this in a comment to the question. – user7440787 Nov 24 '20 at 19:49