在python中复制文件

时间:2013-03-29 15:06:32

标签: python

#!/usr/bin/env python

from os import path, access, R_OK  # W_OK for write permission.
import os`enter code here`
import shutil
import sys
import glob

PATH = 'C:\Windows\PsExec.exe'
PATH2 = 'C:\Windows'
SHARE_PATH = '\\\\blue\\install$\\Tools\\Library'
dirList=os.listdir(SHARE_PATH)

if path.exists(PATH) and path.isfile(PATH) and access(PATH, R_OK):
    print ("File exists and is readable")
elif path.exists(SHARE_PATH) and access(SHARE_PATH, R_OK):
    shutil.copyfile(SHARE_PATH, PATH2)
    print ("Copying File")

我可以在没有错误的情况下运行此脚本但由于某种原因我无法从中复制文件 共享驱动器...现在当我尝试运行该文件时,我收到了以下错误。

Traceback (most recent call last):
  File ".\file_reader3.py", line 18, in <module>
    shutil.copyfile(SHARE_PATH, PATH2)
  File "C:\Python33\lib\shutil.py", line 109, in copyfile
    with open(src, 'rb') as fsrc:
PermissionError: [Errno 13] Permission denied: '\\\\blue\\install$\\Tools\\Library'

2 个答案:

答案 0 :(得分:2)

看起来“shutil.copyfile(SHARE_PATH,PATH2)”这一行试图将一个目录'\\ blue \ install $ \ Tools \ Library'复制到另一个目录'C:\ Windows'。 copyfile只适用于文件。

同样根据文档(http://docs.python.org/2/library/shutil.html),您需要指定完整的文件路径AND名称。所以假设'\\ blue \ install $ \ Tools \ Library'是一个文件(虽然我认为它是一个目录),它试图将它复制到一个名为“c:\ windows”的文件中,而不是复制到该目录中。因此,您需要指定“c:\ windows \ filename”作为第二个参数。

如果您要复制整个目录,请尝试shutil.copytree。

此外,最好只是尝试打开文件并捕获异常,而不是先测试权限。见http://docs.python.org/2/library/os.html#files-and-directories

答案 1 :(得分:2)

from os import path, access, R_OK  # W_OK for write permission.
import os
import shutil
import sys
import glob


PATH = 'C:\Windows\PsExec.exe'
SHARE_PATH = '\\\\blue\\sol\\Tools\\Library\\PsExec.exe'

#This part Will check if the file Exist
if path.exists(PATH) and path.isfile(PATH) and access(PATH, R_OK):
    print ("File exists and is readable")
#This part will Check if the file exist on the server, and copy to the local machine
elif path.exists(SHARE_PATH) and \
     path.isfile(SHARE_PATH) and \
     access(SHARE_PATH, R_OK):
    shutil.copy(SHARE_PATH, PATH)
    print ("Copying File")
相关问题