如何使用变量将文件从网络共享复制到本地磁盘? [英] How to copy a file from a network share to local disk with variables?

查看:184
本文介绍了如何使用变量将文件从网络共享复制到本地磁盘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用以下行:

shutil.copyfile(r"\\mynetworkshare\myfile.txt","C:\TEMP\myfile.txt")

一切正常.但是,我似乎无法弄清楚如何在网络共享路径中使用变量,因为我需要使用"r"(相对?)标志.我想象的最终结果将是这样的:

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.

推荐答案

在您的第一个代码示例中使用的r使字符串成为原始"字符串.在此示例中,这意味着字符串将看到反斜杠,而不会尝试使用它们将\\转义为\.

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 \.

要使第二个代码示例正常工作,请在字符串上使用r,而不要在copyfile命令中使用:

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)

这篇关于如何使用变量将文件从网络共享复制到本地磁盘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆