How to Fix "Python permission denied error" [duplicate] - python

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

Related

Copy Files in directory with specific date

I want to copy files that have specific date. I can filter out the date. Copying makes problems.
import os
from os import walk
import time
from datetime import date, timedelta
import zipfile
import io
import shutil
src = 'K:\\Userfiles'
dest = 'L:\\Userfiles'
date1 = date.today() - timedelta(2)
for root, dirs, files in os.walk(src):
for file in files:
if ( 'zip' in file):
x = file[-18:-8]
d = date1.strftime('%Y-%m-%d')
if x == d:
shutil.copyfile(file, dest)
ERROR is: FileNotFoundError: [Errno 2] No such file or directory.
Traceback (most recent call last):
File "C:/Python37/datetime_finder.py", line 28, in shutil.copyfile(file, 'K:\Userfiles\Ucar\UNZIP')
File "C:\Python37\lib\shutil.py", line 120, in copyfile with open(src, 'rb') as fsrc: FileNotFoundError: [Errno 2] No such file or directory: 'getContents_2019-01-27.csv.zip
Taken from https://docs.python.org/3/library/shutil.html#shutil.copyfile
shutil.copyfile(src, dst, *, follow_symlinks=True)
Copy the contents (no metadata) of the file named src to a file named dst and return dst. src and dst are path names given as strings. dst must be the complete target file name; look at shutil.copy() for a copy that accepts a target directory path.
If I am not mistaken, you are missing setting dest value inside your inner for loop, so shutil.copyfile fails as '' (empty string) does not make sense as second argument. As side note if you want to copy only .zip files it is better to use:
if file.endswith('zip'):
instead of
if ('zip' in file):
which is also True for example for 'my_list_of_zip_files.txt', also keep in mind case-sensitiveness, so it might be better to use following if
if file.lower().endswith('zip'):
You are getting the error in this line shutil.copyfile(file, dest)
Mentioning the full path should fix the problem.
Ex:
shutil.copyfile(os.path.join(root, file), ".")

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

Python Permission Error when reading

import os
import rarfile
file = input("Password List Directory: ")
rarFile = input("Rar File: ")
passwordList = open(os.path.dirname(file+'.txt'),"r")
with this code I am getting the error:
Traceback (most recent call last):
File "C:\Users\Nick L\Desktop\Programming\PythonProgramming\RarCracker.py", line 7, in <module>
passwordList = open(os.path.dirname(file+'.txt'),"r")
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\Nick L\\Desktop'
This is weird because I have full permission to this file as I can edit it and do whatever I want, and I am only trying to read it. Every other question I read on stackoverflow was regarding writing to a file and getting a permissions error.
You're trying to open a directory, not a file, because of the call to dirname on this line:
passwordList = open(os.path.dirname(file+'.txt'),"r")
To open the file instead of the directory containing it, you want something like:
passwordList = open(file + '.txt', 'r')
Or better yet, use the with construct to guarantee that the file is closed after you're done with it.
with open(file + '.txt', 'r') as passwordList:
# Use passwordList here.
...
# passwordList has now been closed for you.
On Linux, trying to open a directory raises an IsADirectoryError in Python 3.5, and an IOError in Python 3.1:
IsADirectoryError: [Errno 21] Is a directory: '/home/kjc/'
I don't have a Windows box to test this on, but according to Daoctor's comment, at least one version of Windows raises a PermissionError when you try to open a directory.
PS: I think you should either trust the user to enter the whole directory-and-file name him- or herself --- without you appending the '.txt' to it --- or you should ask for just the directory, and then append a default filename to it (like os.path.join(directory, 'passwords.txt')).
Either way, asking for a "directory" and then storing it in a variable named file is guaranteed to be confusing, so pick one or the other.
os.path.dirname() will return the Directory in which the file is present not the file path. For example if file.txt is in path= 'C:/Users/Desktop/file.txt' then os.path.dirname(path)wil return 'C:/Users/Desktop' as output, while the open() function expects a file path.
You can change the current working directory to file location and open the file directly.
os.chdir(<File Directory>)
open(<filename>,'r')
or
open(os.path.join(<fileDirectory>,<fileName>),'r')

IOError: [Errno 13] Permission denied: Bulk renaming script

This is one of my first python scripts designed to go into a directory and rename all the files of a certain extension to the same thing. For instance, go into a music directory and change the name of all the album artwork files to something like folder.jpg so that they're easily recognized and displayed by music playing software like foobar2000.
I'm currently getting the error in the title. I've tried:
os.chmod(pathname, 0777)
and
os.chmod(pathname, stat.S_IWOTH)
to allow other entities to edit the directory I'm looking at, but the error remains. I'm not too familiar with Windows's permissions system or with Python so this is mystifying me. Any idea where I'm going wrong?
#Changes file names in every subdirectory of the target directory
import os
import sys
import shutil
#Get target path
pathname = raw_input('Enter path for music directory (ex. C:\\Music): ')
try:
os.chdir(pathname)
except:
print('Failed. Invalid directory?')
sys.exit()
#Get variables for renaming
fn = raw_input('Enter desired file name for all converted files: ')
ft = raw_input('Enter the file extension you want the program to look for (ex. .jpg): ')
outname = fn + ft
#Create path tree
for path, subdirs, files in os.walk (pathname):
#Search tree for files with defined extention
for name in files:
if name.lower().endswith(ft):
#Rename the files
src = os.path.join(path, name)
print (src)
dst = os.path.join(path, outname)
print dst
shutil.move(src, dst)
print('Complete')
A second more benign issue is that when I use a print statement to check on what files are being edited, it seems that before the first .jpg is attempted, the program processes and renamed a file called d:\test\folder.jpg which doesn't exist. This seems to succeed and the program fails in the last loop the second time through, when an existing file is processed. The program runs like this:
>>> ================================ RESTART ================================
>>>
Enter path for music directory (ex. C:\Music): d:\test
Enter desired file name for all converted files: folder
Enter the file extension you want the program to look for (ex. .jpg): .jpg
d:\test\folder.jpg
d:\test\folder.jpg
d:\test\Anathema\Alternative 4\AA.jpg
d:\test\Anathema\Alternative 4\folder.jpg
Traceback (most recent call last):
File "D:\Documents\Programming\Python scripts\Actually useful\bulk_filename_changer.py", line 29, in <module>
shutil.move(src, dst)
File "C:\Python27\lib\shutil.py", line 301, in move
copy2(src, real_dst)
File "C:\Python27\lib\shutil.py", line 130, in copy2
copyfile(src, dst)
File "C:\Python27\lib\shutil.py", line 83, in copyfile
with open(dst, 'wb') as fdst:
IOError: [Errno 13] Permission denied: 'd:\\test\\Anathema\\Alternative 4\\folder.jpg'
>>>
The glitch seems to be benign because it doesn't cause an error, but it might be related to an error I have in the code that leads to the IOError I get when the first "real" file is processed. Beats me...
I am assuming that d: is not a CD drive or something not writable. If so then have you checked the properties of your files? Are any of them read only? There would also need to be more than one of the file type in the folder to cause this, I believe.

Copy contents from one directory and paste in another, IOError: [Errno 13] python

I've looked through the forum at several posts similar to this w/ the same error, but am still unable to fix it. I am getting the IOError: [Errno 13] Permission denied: 'C:/..../.' when using shutil.copy(). Here is the code:
import subprocess, os, shutil
for i in range(1,3):
path = 'C:/Users/TEvans/Desktop/Testing/slope%d' % i
if not os.path.exists(path):
os.makedirs(path)
os.chdir(path)
for j in range(1,4):
path1 = 'C:/Users/TEvans/Desktop/Testing/slope%d/r%d' % (i, j)
if not os.path.exists(path1):
os.makedirs(path1)
src = 'C:/Users/TEvans/Desktop/Testing/PP%d/S%d' % (i, j)
dst = 'C:/Users/TEvans/Desktop/Testing/slope%d/r%d' % (i, j)
shutil.copy(src, dst)
Traceback (most recent call last):
File "sutra.py", line 14, in <module>
shutil.copy(src, dst)
File "C:\Python27\lib\shutil.py", line 117, in copy
copyfile(src, dst)
File "C:\Python27\lib\shutil.py", line 82, in copyfile
with open(src, 'rb') as fsrc:
IOError: [Errno 13] Permission denied: 'C:/Users/TEvans/Desktop/Testing/PP1/S1'
shutil.copy copies a file. You want shutil.copytree to recurisvely copy a whole directory:
import subprocess, os, shutil
for i in range(1,3):
path = 'C:/Users/TEvans/Desktop/Testing/slope%d' % i
if not os.path.exists(path):
os.makedirs(path)
os.chdir(path)
for j in range(1,4):
src = 'C:/Users/TEvans/Desktop/Testing/PP%d/S%d' % (i, j)
dst = 'C:/Users/TEvans/Desktop/Testing/slope%d/r%d' % (i, j)
shutil.copytree(src, dst)
shutil.copy is used for copying a file and not a directory. It needs a file as first parameter and directory or filename as second parameter. If the second parameter is a file name it will do copy and rename the file.
For copying a directory, The best way is to use distutils's dir_util library package.
>>> import distutils.dir_util
>>>
>>> dir(distutils.dir_util)
['DistutilsFileError', 'DistutilsInternalError', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__revision__', '_build_cmdtuple', '_path_created', 'copy_tree', 'create_tree', 'ensure_relative', 'errno', 'log', 'mkpath', 'os', 'remove_tree']
>>>
copy_tree function will help you to copy the whole directory.
Refer to the following definition.
>>> help(distutils.dir_util.copy_tree)
Help on function copy_tree in module distutils.dir_util:
copy_tree(src, dst, preserve_mode=1, preserve_times=1, preserve_symlinks=0, upda
te=0, verbose=1, dry_run=0)
Copy an entire directory tree 'src' to a new location 'dst'.
Both 'src' and 'dst' must be directory names. If 'src' is not a
directory, raise DistutilsFileError. If 'dst' does not exist, it is
created with 'mkpath()'. The end result of the copy is that every
file in 'src' is copied to 'dst', and directories under 'src' are
recursively copied to 'dst'. Return the list of files that were
copied or might have been copied, using their output name. The
return value is unaffected by 'update' or 'dry_run': it is simply
the list of all files under 'src', with the names changed to be
under 'dst'.
'preserve_mode' and 'preserve_times' are the same as for
'copy_file'; note that they only apply to regular files, not to
directories. If 'preserve_symlinks' is true, symlinks will be
copied as symlinks (on platforms that support them!); otherwise
(the default), the destination of the symlink will be copied.
'update' and 'verbose' are the same as for 'copy_file'.
>>>
I guess you are on a Windows machine probably on a Windows Vista or later version; Seeing this is Errno 13 I am pretty much sure you haven't run your script as Administrator. Try to run your script as administrator or if you are executing the script via command prompt try to run the cmd.exe as administrator then execute it.
Try to use backslashes cause you are in windows and while using backslashes try to use raw strings i.e.
path = r'C:\Users\TEvans\Desktop\Testing\slope%d'

Categories