Error on deleting file in a python code

I have a little code that allows me to print images arriving in a folder.

But I'd like them to be deleted just after having been printed - I want to try this on a RaspberryPI and I will not have enough space to store all images.

If someone can help me it would be very much appreciated.

Here is my code:

monRep = "/Users/XX/Desktop/XXX/"
import os, mimetypes, random
while True:
    fpaths = []
    for fname in os.listdir(monRep):
        fpath = os.path.join(monRep, fname)
        if os.path.isfile(fpath):
            mt = mimetypes.guess_type(fpath)[0]
            ext = os.path.splitext(fpath)[1]
            if mt: mt = mt.split('/')[0].lower()
            else: mt = False
            #if ext.lower() in ('.bmp','.pict', '.JPG', '.jpg', '.pdf'): mt = 'image'
            if mt in ('image',): fpaths.append(fpath)

    for fpath in fpaths:
        newpath = fpath.replace('/Users/XX/Desktop/XXX/','/Users/XX/Desktop/XXX2/')
        os.rename(fpath,newpath)
        command = "lpr "+newpath
        print (command)
        os.system(command)

I tried to write at the end

os.remove ('/Users/Aym/Desktop/eden2/')

But then I had this :

SError: [Errno 1] Operation not permitted: '/Users/XX/Desktop/XXX2/'

I tried the shutil method recommanded on this forum

import os
import shutil

for root, dirs, files in os.walk('/Users/XX/Desktop/XXX2/'):
    for f in files:
        os.unlink(os.path.join(root, f))
    for d in dirs:
        shutil.rmtree(os.path.join(root, d))

but nothing happened


I have also less space on a Raspberry. What you can exchange first of all is:

LIST_NAME = ['.jpg', '.bmp', '.mickey_mouse'] 
file = [file for file in os.listdir(CAMERA_DIR) for type_name in LIST_NAME if file.endswith(type_name)]

That is somehow equivalent to your whole search engine above. where LIST_NAME is whatever you look for and CAMERA_DIR == "/Users/XX/Desktop/XXX/"

The lines above will make your code easier and compact without usage of extra modules.

You can use a simple move action from XX to XX2 (shutil module) for each found file under os.path.join(CAMERA_DIR, file_name).

Last step after you print or do whatever, remove completely the XX2 folder with simple command: shutil.rmtree(XX2)

This is definitely work and clean up your code in Python3. Have fun! What I can even recommend is: usage of /tmp/NAMEXX folder. In worst case it is only on the temporary folder of your raspberry!

链接地址: http://www.djcxy.com/p/42432.html

上一篇: 如何使用Python一次删除大量文件夹?

下一篇: 在Python代码中删除文件时出错