i am trying to copy a file from one folder to another, but i am getting "PermissionError: [Errno 13] Permission denied". I am working within my home directory and i am the administrator of the 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.
Thanks in advance for all the support and help.
Perhaps try to use shutil.copyfile instead:
shutil.copyfile(src, dst)
Similar old topic on Why would shutil.copy() raise a permission exception when cp doesn't?
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. 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.
Related
I'm looking to automate the retrieval of minecraft sounds via their hashes. To do this, I developed this piece of code:
list=songname.split("/", -1)
last=int(len(list)-1)
songnamebut=list[last]
listmenos=list[:-1]
destination="/".join(listmenos)
destination = f"son/{destination}"
destination=os.path.abspath(destination)
destination=f"{destination}\\{songnamebut}"
#os.makedirs(os.path.dirname(songname), exist_ok=True)
shutil.copy2(source, destination)
else:
pass
but I have an error which is the following:
Une exception s'est produite : FileNotFoundError
[Errno 2] No such file or directory: 'C:\\Users\\Sunday\\All MC 1.18 Sounds\\son\\minecraft\\sounds\\ambient\\cave\\cave1.ogg'
File "C:\Users\Sunday\All MC 1.18 Sounds\sounds_filter.py", line 28, in <module>
shutil.copy2(source, destination)
I know my code looks weird, for example I created a variable "songnamebut" which only takes the name of the sound as "sounds.ogg" and separated the rest of the file path ("minecraft/sounds/") because, at first, I thought it couldn't create a folder with the same file name.
Thank you in advance!
As I said before, I first tried to change the folder name from "minecraft/sounds/sound.ogg" to "minecraft/sounds/" for the path and "sound.ogg" for the audio file but it didn't work. I also tried to pre-create all the folders by putting the shutil line as a comment and leaving only the os.makedirs. This worked but did not solve the problem.
[Expanded from earlier comments]
The problem was to be that you have an extra son folder in the expected structure that was missing. Hence python couldn't find the destination folder and raised FileNotFoundError
.../All MC 1.18 Sounds/son/minecraft/...
vs
.../All MC 1.18 Sounds/minecraft/...
You can also simplify your code
path, _, last = songname.rpartition("/")
destination = os.path.abspath(os.path.join("son", path))
os.makedirs(destination, exist_ok=True)
shutil.copy2(source, destination)
Or when using pathlib:
import pathlib
file_dir = pathlib.Path(songname).parent
destination = pathlib.Path("son") / file_dir
destination.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, destination)
I have two folders: In, Out - it is not system folder on disk D: - Windows 7. Out contain "myfile.txt" I run the following command in python:
>>> shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
File "C:\Python27\lib\shutil.py", line 82, in copyfile
with open(dst, 'wb') as fdst:
IOError: [Errno 13] Permission denied: 'D:\\In'
What's the problem?
Read the docs:
shutil.copyfile(src, dst)
Copy the contents (no metadata) of the file named src to a file
named dst. dst must be the complete target file name; look at copy()
for a copy that accepts a target directory path.
use
shutil.copy instead of shutil.copyfile
example:
shutil.copy(PathOf_SourceFileName.extension,TargetFolderPath)
Use shutil.copy2 instead of shutil.copyfile
import shutil
shutil.copy2('/src/dir/file.ext','/dst/dir/newname.ext') # file copy to another file
shutil.copy2('/src/file.ext', '/dst/dir') # file copy to diff directory
I solved this problem, you should be the complete target file name for destination
destination = pathdirectory + filename.*
I use this code fir copy wav file with shutil :
# open file with QFileDialog
browse_file = QFileDialog.getOpenFileName(None, 'Open file', 'c:', "wav files (*.wav)")
# get file name
base = os.path.basename(browse_file[0])
os.path.splitext(base)
print(os.path.splitext(base)[1])
# make destination path with file name
destination= "test/" + os.path.splitext(base)[0] + os.path.splitext(base)[1]
shutil.copyfile(browse_file[0], destination)
First of all, make sure that your files aren't locked by Windows, some applications, like MS Office, locks the oppened files.
I got erro 13 when i was is trying to rename a long file list in a directory, but Python was trying to rename some folders that was at the same path of my files. So, if you are not using shutil library, check if it is a directory or file!
import os
path="abc.txt"
if os.path.isfile(path):
#do yor copy here
print("\nIt is a normal file")
Or
if os.path.isdir(path):
print("It is a directory!")
else:
#do yor copy here
print("It is a file!")
Visual Studio 2019
Solution : Administrator provided full Access to this folder "C:\ProgramData\Docker"
it is working.
ERROR: File IO error seen copying files to volume: edgehubdev. Errno: 13, Error Permission denied : [Errno 13] Permission denied: 'C:\ProgramData\Docker\volumes\edgehubdev\_data\edge-chain-ca.cert.pem'
[ERROR]: Failed to run 'iotedgehubdev start -d "C:\Users\radhe.sah\source\repos\testing\AzureIotEdgeApp1\config\deployment.windows-amd64.json" -v' with error: WARNING! Using --password via the CLI is insecure. Use --password-stdin.
ERROR: File IO error seen copying files to volume: edgehubdev. Errno: 13, Error Permission denied : [Errno 13] Permission denied: 'C:\ProgramData\Docker\volumes\edgehubdev\_data\edge-chain-ca.cert.pem'
use
> from shutil import copyfile
>
> copyfile(src, dst)
for src and dst use:
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
This works for me:
import os
import shutil
import random
dir = r'E:/up/2000_img'
output_dir = r'E:/train_test_split/out_dir'
files = [file for file in os.listdir(dir) if os.path.isfile(os.path.join(dir, file))]
if len(files) < 200:
# for file in files:
# shutil.copyfile(os.path.join(dir, file), dst)
pass
else:
# Amount of random files you'd like to select
random_amount = 10
for x in range(random_amount):
if len(files) == 0:
break
else:
file = random.choice(files)
shutil.copyfile(os.path.join(dir, file), os.path.join(output_dir, file))
Make sure you aren't in (locked) any of the the files you're trying to use shutil.copy in.
This should assist in solving your problem
I avoid this error by doing this:
Import lib 'pdb' and insert 'pdb.set_trace()' before 'shutil.copyfile', it would just like this:
import pdb
...
print(dst)
pdb.set_trace()
shutil.copyfile(src,dst)
run the python file in a terminal, it will execute to the line 'pdb.set_trace()', and now the 'dst' file will print out.
copy the 'src' file by myself, and substitute and remove the 'dst' file which has been created by the above code.
Then input 'c' and click the 'Enter' key in the terminal to execute the following code.
well the questionis old, for new viewer of Python 3.6
use
shutil.copyfile( "D:\Out\myfile.txt", "D:\In" )
instead of
shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
r argument is passed for reading file not for copying
I have a functionality in my Python which backups a particular directory everyday. The backup steps include compressing the directory. I am using shutil.make_archive to compress the directory.
But now I am facing a permission issue when the directory I compress contains files which I do not have access to.
In this case, I just want to skip that file and then go ahead with compression of the remaining files. How do I achieve this ?
I searched SO and came across this answer, which shows how to zip a directory from using zipfile library. In this case, I can just check if a particular file throws an exception and ignore it.
Is this the only way or is there an easier way ?
My code (just uses shutil.make_archive):
shutil.make_archive(filename, "zip", foldername)
The code in the answer which I have modified for my use:
def zipdir(path, ziph):
# ziph is zipfile handle
for root, dirs, files in os.walk(path):
for file in files:
try:
ziph.write(os.path.join(root, file))
except PermissionError as e:
continue
if __name__ == '__main__':
zipf = zipfile.ZipFile('Python.zip', 'w', zipfile.ZIP_DEFLATED)
zipdir('tmp/', zipf)
zipf.close()
Please tell me if there is an easier/efficient solution to my issue.
I know this is ancient history, but you can use copytree and pass in a custom copy function that suppresses the permissions errors:
import os
#Adapted from python shutil source code.
def copyIgnorePermissionError(src, dst, *, follow_symlinks=True):
"""Copy data and metadata. Return the file's destination.
Metadata is copied with copystat(). Please see the copystat function
for more information.
The destination may be a directory.
If follow_symlinks is false, symlinks won't be followed. This
resembles GNU's "cp -P src dst".
"""
if os.path.isdir(dst):
dst = os.path.join(dst, os.path.basename(src))
#try the copy. If it gives us any lip about permission errors,
#we're going to just suppress them here. If for some reason
#a non-permission error happens, then raise it.
try:
copyfile(src, dst, follow_symlinks=follow_symlinks)
copystat(src, dst, follow_symlinks=follow_symlinks)
except PermissionError:
pass
except Exception as e:
raise(e)
finally:
return dst
#copy the source to some safe destination
shutil.copytree(aSource, aCopyDestination, copy_function=copyIgnorePermissionError)
That will make a copy of all the files and directories that you can access at your permission level. Then you can use shutil.make_archive to create the archive of this copy, then delete the copy.
I get this error:
IOError [Error 21] is a directory
when I try to copy a file to an existing directory. I do it like this:
shutil.copyfile(src, dst)
where src is a file and dst is an existing directory. What I'm doing wrong?
You're using the wrong function. You might want "copy":
https://docs.python.org/2/library/shutil.html
You have already answered yourself in the question.
dst should be the path to the copied file. So if you want to copy the file to /var/lib/my/ and your file is called f1 then dst should be /var/lib/my/f1.txt
Try to use shutil.copy as suggested here by john-estess
shutil.copy(src, dst)
or try to fix this using the following snippet
shutil.copyfile(src, '%s/%s' % (dst, src.split('/')[-1]))
Assuming src is the path of the file you want to copy, such as /var/log/apache/access.log, and dst is the path to the directory, where you want to copy the file, for example, /var/lib/my then the new destination is /var/lib/my/access.log.
See code snippet to see how the source is the path to a file, AND the destination is also a path to a file (that doesn't yet exist until you run this function).
for file in orig_files:
shutil.copyfile(SOURCE_PATH + file_name, DEST_PATH + file_name)
I'm trying to run my web application at www.pythonanywhere.com. The problem is that it loads couple files into the memory and during this process it returns IOError: [Errno 2] No such file or directory:. But I'm sure that the directory is there.
The folder is:
mysite/files/dictionaryA
2015-01-30 15:06:44,101 : File "/home/tox/mysite/Data.py", line 241, in loadDictionaryAB
2015-01-30 15:06:44,102 : with open(path.relpath('files/dictionaryA'),'rb') as f:
2015-01-30 15:06:44,102 :IOError: [Errno 2] No such file or directory: 'files/dictionaryA'
The Data.py is in mysite/files dictionary, so there should be no problem. Linux and Windows on my computer has not problem with that.
I'll appreciate any advices.
The current working directory is where the interpreter was started and not where your .py script is. Either use an absolute path to your files, or make sure you know where you are. os.curdir shows you the current directory. Your home folder can be obtained by expanduser("~") in the os.path module. After you figure out where you are you can easily join the path, or os.chdir() into the folder you require.
from os.path import expanduser
homedir = expanduser("~")
with open(os.path.join(homedir, "mysite/files/dictionaryA"), 'rb') as f:
# Work with dictionaryA
The above should work for your case.