简体   繁体   English

在Python中移除USB设备上的树

[英]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: 我使用以下代码删除USB设备上的树,但是我收到OSError:

I also ran the code with sudo python. 我还使用sudo python运行了代码。

import shutil 进口壁垒

import os 导入操作系统

src = "/media/device/my_folder" src =“ / media / device / my_folder”

if os.path.exists(dst): 如果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. 我刚在另一个脚本中使用shutil.copytree(src,dst)首先将文件写入设备。 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. 但是,USB设备在复制过程中被删除了,这可能是导致我遇到的问题,因为除一半复制的文件以外的所有其他文件都被删除了。

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. 如果在尝试使用shutil.rmtree之前使用chmod正确设置了权限,则它应该可以工作。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM