If I use the following line:
shutil.copyfile(r"\\mynetworkshare\myfile.txt","C:\TEMP\myfile.txt")
everything works fine. However, what I can't seem to figure out is how to use a variable with the network share path, because I need the 'r' (relative?) flag. The end result I would imagine would be something like:
source_path = "\\mynetworkshare"
dest_path = "C:\TEMP"
file_name = "\\myfile.txt"
shutil.copyfile(r source_path + file_name,dest_path + file_name)
But I have had no luck with different variations of this approach.
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 thecopyfile
command:From your example paths, it's clear that we are discussing the
Windows OS
. Python implementation on this OS use a common (C
) runtime library that accepts forward slashes as equivalent to back-slashes. This way you can avoid escape char issues.Note that filename composition is handled by os.path.join:
The
r
is for "raw string", not for relative. When you don't prefix your string withr
, 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.This looks like an escaping issue - as balpha says, the
r
makes the\
character a literal, rather than a control sequence. Have you tried:(Using an interactive python session, you can see the following: