Question

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?

Était-ce utile?

La solution

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)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top