使用shutil.copyFile将文件从网络位置复制到本地桌面的Python显示权限den4ied

时间:2016-03-12 22:46:40

标签: python-2.7 shutil

我正在将软件的构建文件从网络位置的目录复制到本地计算机。 我首先阅读build.txt文件以阅读最新的构建版本。 然后,我可以将最新的构建文件复制到本地计算机,即将最新的构建文件部署到我的本地计算机。

我已经正确设置了src目录路径,已经读取了构建文本文件。 我打印到控制台的路径并将路径复制到Windows资源管理器以检查路径是否正确。路径存在。

我正在使用shutil.copyFile

运行我的代码时,我的权限被拒绝了。完整的错误跟踪是:

Traceback (most recent call last):
  File "C:\Webdriver\ClearCore 501 Regression Test\ClearCore 501 - Regression Test\Base\BaseTestCase.py", line 34, in setUpClass
    shutil.copyfile(src2, dest_file)
  File "C:\Python27\lib\shutil.py", line 82, in copyfile
    with open(src, 'rb') as fsrc:
IOError: [Errno 13] Permission denied: '\\\\STORAGE-1\\Builds\\clearcore4\\5_1_1\\engine\\ClearCore4_b5_1_1_v5_1_1_5306\\deploy\\engine'

我的Python代码片段用于读取build.txt文件并将文件从src复制到目标:

from ConfigParser import SafeConfigParser
import shutil

class BaseTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
    # copy build file
    build_text_file_directory = r"\\STORAGE-1\Builds\clearcore4\autotest"
    dest_file = r"C:\Riaz\clearcore_5_1_1_copy_test_using_shutil_tool\engine"
    build_config = SafeConfigParser()
    fn = os.path.join(build_text_file_directory, "5_1_1_build.txt")
    build_config.read(fn)
    label = build_config.get("build", "label")
    src = r"\\STORAGE-1\Builds\clearcore4\5_1_1\engine\%s" % label
    src2 = os.path.join(src, r"deploy\engine")
    shutil.copyfile(src2, dest_file)

如何解决被拒绝的权限并将文件复制到目的地? 谢谢, 里亚兹

1 个答案:

答案 0 :(得分:0)

我现在设法解决了这个问题,问题是它试图复制一个目录。 shutilcopyfile复制文件,而不是目录。我修改了我的代码以遍历目录并从子目录中复制文件。 如果子目录不存在,它将创建它并将文件复制到它。

我的工作代码是:

    build_text_file_directory = r"\\STORAGE-1\Builds\clearcore4\autotest"
    dest = r"C:\Riaz\ClearCore501 - copy latest build copy test\engine"
    build_config = SafeConfigParser()
    fn = os.path.join(build_text_file_directory, "5_1_1_build.txt")
    build_config.read(fn)
    label = build_config.get("build", "label")
    src = r"\\STORAGE-1\Builds\clearcore4\5_1_1\engine\%s\deploy\engine" % label
    for src_dir, dirs, files in os.walk(src):  
        if "gazdb" in dirs:  # Do not copy "gazdb" directory.
            dirs.remove("gazdb")
        dest_dir = os.path.join(dest, src_dir[len(src) + 1:])
        if not os.path.exists(dest_dir):
            os.makedirs(dest_dir)
        for filename in files:
            src_file = os.path.join(src_dir, filename)
            dest_file = os.path.join(dest_dir, filename)
            # print("%s -> %s" % (src_file, dest_file))
            shutil.copyfile(src_file, dest_file)