Why would shutil.copy() raise a permission exception when cp doesn't? - python

shutil.copy() is raising a permissions error:
Traceback (most recent call last):
File "copy-test.py", line 3, in <module>
shutil.copy('src/images/ajax-loader-000000-e3e3e3.gif', 'bin/styles/blacktie/images')
File "/usr/lib/python2.7/shutil.py", line 118, in copy
copymode(src, dst)
File "/usr/lib/python2.7/shutil.py", line 91, in copymode
os.chmod(dst, mode)
OSError: [Errno 1] Operation not permitted: 'bin/styles/blacktie/images/ajax-loader-000000-e3e3e3.gif'
copy-test.py:
import shutil
shutil.copy('src/images/ajax-loader-000000-e3e3e3.gif', 'bin/styles/blacktie/images')
I am running copy-test.py from the command line:
python copy-test.py
But running cp from the command line on the same file to the same destination doesn't cause an error. Why?

The operation that is failing is chmod, not the copy itself:
File "/usr/lib/python2.7/shutil.py", line 91, in copymode
os.chmod(dst, mode)
OSError: [Errno 1] Operation not permitted: 'bin/styles/blacktie/images/ajax-loader-000000-e3e3e3.gif'
This indicates that the file already exists and is owned by another user.
shutil.copy is specified to copy permission bits. If you only want the file contents to be copied, use shutil.copyfile(src, dst), or shutil.copyfile(src, os.path.join(dst, os.path.basename(src))) if dst is a directory.
A function that works with dst either a file or a directory and does not copy permission bits:
def copy(src, dst):
if os.path.isdir(dst):
dst = os.path.join(dst, os.path.basename(src))
shutil.copyfile(src, dst)

This form worked for me:
shutil.copy('/src_path/filename','/dest_path/filename')

I had this exact same issue... using shutil.copyfile() was a good workaround.... however, I completely FIXED the issue by simply rebooting Windows 10 OS.

This work for me:
I don't use shutil I use shell command for copy, and run shell command in python.
Code:
import os
my_source= '/src_path/filename'
my_dest= '/dest_path/filename'
os.system('sudo cp ' +my_source + my_dest ) # 'sudo cp /src_path/filename /dest_path/filename '
and that work for me.

This is kind of a guess, but the first thing that pops out at me:
'bin/styles/blacktie/images'
You have no trailing slash. While I'm not sure of the implementation of shutil.copy(), I can tell you that cp will act differently depending on what OS you're running it on. Most likely, on your system, cp is being smart and noticing that images is a directory, and copying the file into it.
However, without the trailing slash, shutil.copy() may be interpreting it as a file, not checking, and raising the exception when it's unable to create a file named images.
In short, try this:
'bin/styles/blacktie/images/'

Arguments must be:
shutil.copy('src/images/ajax-loader-000000-e3e3e3.gif', 'bin/styles/blacktie/images.ajax-loader-000000-e3e3e3.gif')

Related

how to elevate python file

Today I was working on a python script that will copy a folder in one directory and paste it in another directory.Everything was going fine but when I ran my code,It gives me an eror masseges like this:
Traceback (most recent call last):
File "c:\Users\sudam\OneDrive\Desktop\programming\python\projects\file_syncer\syncer.py", line 9, in <module>
shutil.copy(pearent_directry , moving_directry)
File "C:\Users\sudam\AppData\Local\Programs\Python\Python310\lib\shutil.py", line 417, in copy
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "C:\Users\sudam\AppData\Local\Programs\Python\Python310\lib\shutil.py", line 254, in copyfile
with open(src, 'rb') as fsrc:
PermissionError: [Errno 13] Permission denied: 'C:/Users/sudam/OneDrive/Documents/Rainmeter'
and here is my code:
print('file syncer version 1.0')
import shutil
from elevate import elevate
elevate()
pearent_directry = 'C:/Users/sudam/OneDrive/Documents/Rainmeter'
moving_directry = 'D:/sync'
shutil.copy(pearent_directry , moving_directry)
print('process has finished with error code:0')
any yes,I did use elevate to try to get admin rights but,It doesn't work either.
Can somebody please help me out in solving this issue?
Bro, it's easier to change the code to fix your problem.
from distutils.dir_util import copy_tree
a = "The path to the file"
b = "The path to the file"
copy_tree(a, b)
print("Process finished")
Also read the PEP8 documentation.

python pysftp [Errno 13] Permission denied:

I'm trying to copy files from SFTP server .
I can connect using python pysftp .
I can run:
data = srv.listdir()
for i in data:
print I
And I get the Directory list. But when I try
sftp.put (localpath,"file_name.txt")
I get
>"IOError: [Errno 13] Permission denied: 'C:\\....."
I have permission to that folder, because I can run MKDIR and it creates a directory in that file path. I have tried many many different ways but no luck so far, any help is truly appreciated.
import pysftp
import os
def sftpExample():
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
with pysftp.Connection('HOST', username='username', password='Password', cnopts=cnopts) as sftp :
print 'connected '
localpath="C:\\new project\\new"
remotepath="/folder1"
sftp.put(localpath,"infso.txt")
sftp.put(localpath,remotepath)
sftp.getfo (remotepath, localpath )
srv.get_r(localpath, remotepath)
srv.close()
sftpExample()
I get this error code:
Traceback (most recent call last):
File "db_backup.py", line 42, in <module>
sftpExample()
File "db_backup.py", line 17, in sftpExample
sftp.put(localpath,"GT-Dallas SFTP infso.txt")
File "c:\Python27\lib\site-packages\pysftp\__init_.py", line 364, in put
confirm=confirm)
File "c:\Python27\lib\site-packages\paramiko\sftp_client.py", line 720, in put
with open(localpath, 'rb') as fl:
IOError: [Errno 13] Permission denied: "C:\\new project\\new"
I've tried all different ways to copy the file as you see however I've had no luck so far.
The issue is that you're trying to save a file as a directory which, at least in my experience, is what throws the Permission Denied error in pysftp.
Change this line of code:
localpath="C:\\new project\\new"
To this:
localpath="C:\\new project\\new\\infso.txt"
NOTE: infso.txt can be anything you want to name the local file being downloaded. I've used the same name here as the remote file's name from your example for symmetry and simplicity.
There are a few things that might be causing your issue, but the one that stands out to me comes from your error message:
IOError: [Errno 13] Permission denied: "C:\\new project\\new"
It might be that you need to escape the space ("\ ") or put it in a raw string r"C:\My Path With Spaces"
But in any case, I would avoid using spaces in your filenames, and you should rename your project folder to something like new_project or newproject.
Another thing that would make your life easier is if you compressed your directory into a single archive file (.tgz or .zip or something) and transfer that file.

Copying files into multiple directories using Python Shutil

I am trying to use shutil.copytree to copy a directory onto multiple other directories. I can't get it to work. I'm pretty sure I just need to implement ignore_errors=True, but I cant get it to work. How should I go about implementing 'ignore_errors=True' into
for CopyHere in DeleteThis:
for CopyThis in FilestoCopy:
shutil.copytree(CopyThis, CopyHere)
print('Files have been copied')
My code is as follows:
import shutil
import time
DeleteThis = ['E:', 'F:']
FilestoCopy = ['C:\\Users\\2402neha\\Desktop\\Hehe']
for Directory_to_delete in DeleteThis:
shutil.rmtree(Directory_to_delete, ignore_errors=True)
print('Directories have been wiped')
time.sleep(2)
for CopyHere in DeleteThis:
for CopyThis in FilestoCopy:
shutil.copytree(CopyThis, CopyHere)
print('Files have been copied')
Here are the error messages I get:
Traceback (most recent call last):
File "C:\Users\2402neha\OneDrive\Python\Dis Cleaner\Copy paste test.py", line 17, in <module>
shutil.copytree(CopyThis, CopyHere)
File "C:\Users\2402neha\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 309, in copytree
os.makedirs(dst)
File "C:\Users\2402neha\AppData\Local\Programs\Python\Python35\lib\os.py", line 241, in makedirs
mkdir(name, mode)
PermissionError: [WinError 5] Ingen tilgang: 'E:'
Your destination is E:
The destination directory needs to not exist.
From the documentation for shutil.copytree:
shutil.copytree(src, dst, symlinks=False, ignore=None)
Recursively copy an entire directory tree rooted at src. The destination directory, named by dst, must not already exist; it will be created as well as missing parent directories.
You probably want the directory name you're copying and to join it with the destination:
directory = os.path.basename(CopyThis)
destination = os.path.join(CopyHere, directory)
shutil.copytree(CopyThis, destination)

Removing a tree on a USB device in Python

I've used the following code to remove a tree on a USB device however I'm receiving an OSError:
I also ran the code with sudo python.
import shutil
import os
src = "/media/device/my_folder"
if os.path.exists(dst):
shutil.rmtree(dst)
I've just used shutil.copytree(src, dst) in another script to write the files to the device in the first place. However the USB device was removed during the copy, this is probably causing the issue I'm having as all other files except the one that was half copied have been removed okay.
I'm getting the following traceback:
Traceback (most recent call last):
File "writetousb/tests/deleteTest.py", line 32, in <module>
shutil.rmtree(src)
File "/usr/lib/python2.7/shutil.py", line 252, in rmtree
onerror(os.remove, fullname, sys.exc_info())
File "/usr/lib/python2.7/shutil.py", line 250, in rmtree
os.remove(fullname)
OSError: [Errno 30] Read-only file system: '/media/device/21823/21916.jpg'
So I'm guessing I'll need to change the permissions of the folder and it's files before I remove them?
If I use chmod to set the permissions correctly before I try to use shutil.rmtree then it should work. I'm going to test this and provide an update when I know it works.
I can confirm the solution works.
import shutil
import os
src = "/media/device/my_folder"
if os.path.exists(dst):
os.chmod(dst, 0o777)
for root,dirs,_ in os.walk(dst):
for d in dirs :
os.chmod(os.path.join(root,d) , 0o777)
shutil.rmtree(dst)

Script not working since windows 7

I have the following script which worked fine on XP, since I have a new PC on Windows 7 Professional the code has stopped working
import os
import shutil
from time import strftime
logsdir="c:\logs"
zipdir="c:\logs\puttylogs\zipped_logs"
zip_program="zip.exe"
for files in os.listdir(logsdir):
if files.endswith(".log"):
files1=files+"."+strftime("%Y-%m-%d")+".zip"
os.chdir(logsdir)
os.system(zip_program + " " + files1 +" "+ files)
shutil.move(files1, zipdir)
os.remove(files)
The error I am getting is
U:>python logs.py
zip warning: name not matched: ping_dms_155.log
zip error: Nothing to do! (ping_dms_155.log.2013-05-14.zip)
Traceback (most recent call last):
File "logs.py", line 24, in <module>
shutil.move(files1, zipdir)
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 82, in copyfile
with open(src, 'rb') as fsrc:
IOError: [Errno 2] No such file or directory: 'ping_dms_155.log.2013-05-14.zip'
I can't think why it would stop working, thanks in advance
It seems you do have zip.exe on your windows 7 machine from the error, but it may not be a version compatible with Windows 7.
Check in logsdir to see if the file you modify (ping_dms_155.log.2013-05-14.zip) already exists. If all of these are true I would suggest using python module zipfile.
Your path strings aren't escaped properly.
logsdir="c:\logs"
zipdir="c:\logs\puttylogs\zipped_logs"
should be:
logsdir=r"c:\logs"
zipdir=r"c:\logs\puttylogs\zipped_logs"
The directory c:ogs doesn't exist. Running it manually worked because you changed to the log directory. It ran on XP because... well, you didn't run this exact script on XP because it wouldn't work there either.
I have got this to work by changing the os.system to subprocess so the code now looks like
import os
import shutil
from time import strftime
import subprocess
logsdir="c:\logs"
zipdir="c:\logs\puttylogs\zipped_logs"
zip_program="zip.exe"
for files in os.listdir(logsdir):
if files.endswith(".log"):
files1=files+"."+strftime("%Y%m%d")+".zip"
os.chdir(logsdir)
subprocess.call([zip_program,files1, files])
shutil.move(files1, zipdir)
os.remove(files)

Categories