How to copy a file from a network share to local disk with variables? How to copy a file from a network share to local disk with variables? python python

How to copy a file from a network share to local disk with variables?


The r used in your first code example is making the string a "raw" string. In this example, that means the string will see the backslashes and not try to use them to escape \\ to just \.

To get your second code sample working, you'd use the r on the strings, and not in the copyfile command:

source_path = r"\\mynetworkshare"dest_path = r"C:\TEMP"file_name = "\\myfile.txt"shutil.copyfile(source_path + file_name, dest_path + file_name)


The r is for "raw string", not for relative. When you don't prefix your string with r, Python will treat the backslash "\" as an escape character.

So when your string contains backslashes, you either have to put an r before it, or put two backslashes for each single one you want to appear.

>>> r"\\myfile" == "\\\\myfile"True


This looks like an escaping issue - as balpha says, the r makes the \ character a literal, rather than a control sequence. Have you tried:

source_path = r"\\mynetworkshare"dest_path = r"C:\TEMP"filename = r"\my_file.txt"shutil.copyfile(source_path + filename, dest_path + filename)

(Using an interactive python session, you can see the following:

>>> source_path = r"\\mynetworkshare">>> dest_path = r"C:\TEMP">>> filename = r"\my_file.txt">>> print (source_path + filename)\\mynetworkshare\my_file.txt>>> print (dest_path + filename)C:\TEMP\my_file.txt