简体   繁体   English

PermissionError: [Errno 13] 权限被拒绝 @ PYTHON

[英]PermissionError: [Errno 13] Permission denied @ PYTHON

i am trying to copy a file from one folder to another, but i am getting "PermissionError: [Errno 13] Permission denied".我试图将文件从一个文件夹复制到另一个文件夹,但我收到“PermissionError: [Errno 13] Permission denied”。 I am working within my home directory and i am the administrator of the PC.我在我的主目录中工作,我是 PC 的管理员。 Went through many other previous posts .. tried all the options that are to my knowledge (newbie to programming) ... need some help.浏览了许多其他以前的帖子......尝试了我所知的所有选项(编程新手)......需要一些帮助。

import os
import shutil

src = "C:\\Users\\chzia\\Scripts\\test" # the file lab.txt is in this folder that needs to be copied to testcp folder.
dst = "C:\\Users\\chzia\\Scripts\\testcp"

for file in os.listdir(src):
  src_file = os.path.join(src, file)
  dst_file = os.path.join(dst, file)
  #shutil.copymode(src, dst) # i have tried these options too same error
  #shutil.copyfile(src, dst) # i have tried these options too same error
  shutil.copy(src, dst)

My target is to create an .exe that copies a file from the network location to a specific folder on a pc where the .exe is run.我的目标是创建一个 .exe,将文件从网络位置复制到运行 .exe 的 PC 上的特定文件夹。 Thanks in advance for all the support and help.在此先感谢大家的支持和帮助。

Perhaps try to use shutil.copyfile instead:也许尝试使用shutil.copyfile代替:

shutil.copyfile(src, dst)

Similar old topic on Why would shutil.copy() raise a permission exception when cp doesn't?类似的旧主题为什么当 cp 没有时shutil.copy() 会引发权限异常?

I am sure I am late, but I ran into the same problem.我确定我迟到了,但我遇到了同样的问题。

I noticed that in my case the problem is that the subfolder already exists.我注意到在我的情况下,问题是子文件夹已经存在。 If I delete the folder at the start (it is OK in my case).如果我在开始时删除文件夹(在我的情况下可以)。

import os
import shutil    

dst = "C:\\Users\\chzia\\Scripts\\testcp" # target folder


def checkFolder(path):

    try:
        os.stat(path)
        shutil.rmtree(path)
    except:
        os.mkdir(path)


checkFolder(dst)

If you Googled the exception and ended-up here, remember to provide the absolute/full path when using copy & copyfile from shutil .如果您在 Google 上搜索异常并在此处结束,请记住在使用来自shutil copy & copyfile时提供绝对/完整路径 For example,例如,

 abs_src_path = os.path.abspath(relative_file_path)
 abs_dst_path = os.path.abspath(relative_dst_path)
 shutil.copy(abs_src_path , abs_dst_path)

In the question above that is already done, but you might be the one who is mislead by the error message.在上面的问题中,已经完成了,但您可能是被错误消息误导的人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM