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)
Related
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.
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)
I'm trying to code a little script that watches a defined directory with a while-loop. Every file or directory that is in this directory is compressed to RAR and moved to another directory after the process is completed.
My problem: everytime I copy a file or folder to this directory, the script doesn't wait and startes the process the second it sees a new file or folder. But when the files or folders are bigger than a few kilobytes the loop breaks with a permission error.
Since I'm a Python beginner I don't know which module to use. Is there a checking module to see if the file or folder that the tool wants to process is used by another process? Or am I going in the wrong direction?
Edit: added the code for directory-only listening:
watchDir = "L:\\PythonTest\\testfolder\\"
finishedDir = "L:\\PythonTest\\finishedfolders\\"
rarfilesDir = "L:\\PythonTest\\rarfiles\\"
rarExe = "L:\\PythonTest\\rar.exe"
rarExtension = ".rar"
rarCommand = "a"
while True:
dirList = [name for name in os.listdir(watchDir) if os.path.isdir(os.path.join(watchDir,name))]
for entryName in dirList:
if not os.path.exists((os.path.join(finishedDir,entryName))):
sourcePath = os.path.join(watchDir,entryName)
entryNameStripped = entryName.replace(" ", "")
os.chdir(watchDir)
archiveName = rarfilesDir+entryNameStripped+rarExtension
subprocesscall = [rarExe, rarCommand, archiveName, entryName]
subprocess.call(subprocesscall, shell=True)
shutil.move(sourcePath,finishedDir)
When I run the script and try to add a file of several GB (named #filename# in the following lines) these errors occur:
Creating archive L:\PythonTest\rarfiles\#filename#.rar
Cannot open #filename#
The process cannot access the file, since it's used by another process.
Adding #filename# OK
WARNING: Cannot open 1 file
Done
Traceback (most recent call last):
File "C:\Python34\lib\shutil.py", line 522, in move
os.rename(src, real_dst)
PermissionError: [WinError 5] Access denied: #filepath#
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "L:/Python Test/test.py", line 35, in <module>
shutil.move(sourcePath,finishedDir)
File "C:\Python34\lib\shutil.py", line 531, in move
copytree(src, real_dst, symlinks=True)
File "C:\Python34\lib\shutil.py", line 342, in copytree
raise Error(errors)
shutil.Error: #filepath#
instead of using os.listdir, you can use os.walk, os.walk yields 3 tuple dirpath(path of directory,filenames(all files in that dirpath),dirnames(all the sub directories in dirpath)
for x,y,z in os.walk('path-of-directory'):
do you stuff with x,y,z the three tuples
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)
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')