-2

So, as SO keeps suggesting me, I do not want to replace double backslashes, I want python to understand them.

I need to copy files from a windows distant directory to my local machine.

For example, a "equivalent" (even if not) in shell (with windows paths):

cp \\directory\subdirectory\file ./mylocalfile

But python does not even understand double backslashes in strings:

source = "\\dir\subdir\file"
print(source)

$ python __main__.py 
__main__.py:1: DeprecationWarning: invalid escape sequence \s
  source = "\\dir\subdir\file"
\dir\subdir
           ile

Is Python able to understand windows paths (with double backslashes) in order to perform file copies ?

3
  • 2
    Use a raw string literal Commented Jul 28, 2021 at 10:16
  • 2
    Use the r prefix on your string literal. Commented Jul 28, 2021 at 10:16
  • The problem is not "make Python 3 understand double backslash"; the problem is "make Python 3 treat backslash as a literal backslash instead of an escape sequence". Notice how the warning is being reported for the single backslash, not for the double backslash? Commented Aug 4, 2022 at 21:22

1 Answer 1

0

You can try this also:

source = r"\dir\subdir\file"
print(source)
# \dir\subdir\file

You can solve this issue by using this raw string also.
What we are doing here is making "\dir\subdir\file" to raw string by using r at first.

You can visit here for some other information.

raw strings are raw string literals that treat backslash (\ ) as a literal character. For example, if we try to print a string with a “\n” inside, it will add one line break. But if we mark it as a raw string, it will simply print out the “\n” as a normal character.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.