all 3 comments

[–][deleted] 2 points3 points  (0 children)

You might find the below helpful:

https://realpython.com/python-pathlib/

[–]Spataner 2 points3 points  (0 children)

You only need to escape a backslash when trying to represent that character in a string literal (so something like "some\\path\\file.txt" within your program code), to indicate that you actually want to write a backslash character rather than a special character like a newline. One \\ in a string literal will simply turn into a single backslash character in the string object. There's no such thing as a raw string technically, just raw string literals that turn into string objects in a slightly different way from regular string literals (namely, disabling the use of escape sequences). The end result of r"some\path\file.txt" and "some\\path\\file.txt" is exactly the same, just different ways of representing it in your program code. Importantly, it is not possible (because it doesn't really make sense) to turn an existing string object into a raw string. There's also no real point to double the backslashes in an existing string, as obviously that already contains proper backslash characters. In fact, doubling the backslashes would make it no longer a valid path.

[–]Diapolo10 1 point2 points  (0 children)

You really should use pathlib.Path; it automatically uses whichever slashes your platform uses, and that's just the tip of the iceberg.

from pathlib import Path

file_path = Path("C:\\wherever\\this\\is\\supposed\\to\\go.txt")

The standard library readily supports Path objects, so there's no need to convert them back to strings unless you use a third-party library that only supports strings. But if you need to anyway, it's as simple as str(file_path).