iT邦幫忙

0

突然不能刪除檔案

這個代碼原本用得好好地都沒問題
在我重裝軟體後就出問題
無法刪除他檢測到的圖片

import os
import shutil
from PIL import Image

def is_valid_jpg(jpg_file):
    with open(jpg_file, 'rb') as f:
        f.seek(-2, 2)
        buf = f.read()
        return buf == b'\xff\xd9'

def is_valid_png(png_file):
    with open(png_file, 'rb') as f:
        f.seek(-3, 2)
        buf = f.read()
        if buf == b'\x60\x82\x00':
            return True
        elif buf[1:] == b'\x60\x82':
            return True
        else:
            return False

def is_valid_pic(pic_file):
    if pic_file.endswith('jpeg'):
        return is_valid_jpg(pic_file)

    elif pic_file.endswith('png'):
        return is_valid_png(pic_file)
    else:
        return False
    
DirList=["D:\\long\\Desktop\\123"]
for path in DirList:
    for dirPath, dirNames, fileNames in os.walk(path):
        for file in fileNames:
            pic_file = os.path.join(dirPath,file)
            ext=pic_file.split('.')[-1]
            if not is_valid_pic(pic_file):
                if ext == 'jpg' or ext == 'png':
                    try:
                        img = Image.open(pic_file)
                        img.load()
                    except Exception as e:
                        #print(e)
                        print(pic_file)
                        #os.remove(pic_file)#刪除檔案

https://www.sendspace.com/file/5xd5ut
這裡有3個檔案
分別是代碼、正常圖、毀損圖
有誰可以幫忙測試一下嗎
版本是Python 3.6.8

s4028600 iT邦新手 5 級 ‧ 2019-12-30 01:31:09 檢舉
```
x=[]

x.append(pic_file)

os.remove(x[0])
```
這是我另外想的方法
還沒成型
但是淺水員給的方法快多了
雖然還是不清楚為何之前可以
感謝各位的見解
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
2
淺水員
iT邦大師 6 級 ‧ 2019-12-30 00:41:17
最佳解答
if ext == 'jpg' or ext == 'png':
    try:
        img = None
        img = Image.open(pic_file)
        img.load()
    except Exception as e:
        if(img):
            img.close() #要關閉才能刪除
        print(pic_file)
        os.remove(pic_file)#刪除檔案
看更多先前的回應...收起先前的回應...
s4028600 iT邦新手 5 級 ‧ 2019-12-30 01:18:23 檢舉

原本還想說試過了沒用
結果成功了
我想問一下
img = None
if(img):
分別有什麼用意嗎

淺水員 iT邦大師 6 級 ‧ 2019-12-30 01:21:23 檢舉

如果 pic_file 無法被 Image.open(pic_file) 開啟,就不用 close 了。
我只是想確認那個 Exception 是因為 open 還是 load 造成。

s4028600 iT邦新手 5 級 ‧ 2019-12-30 01:42:00 檢舉

看報錯應該是.load()的關係 不清楚...
img = None感覺是將變數歸零?
if(img):是怎麼成立條件的啊 印象中if都是這樣 if a>b:有數學符號
這兩條刪除好像也能運作

小魚 iT邦大師 1 級 ‧ 2019-12-30 08:14:51 檢舉

if 裡面放的其實是 布林值

s4028600 iT邦新手 5 級 ‧ 2019-12-30 09:41:03 檢舉

小魚
所以if(img):的意思是
條件img為true嗎?

小魚 iT邦大師 1 級 ‧ 2019-12-30 09:50:58 檢舉

通常是如果物件不是NULL(None),
if條件就會成立.

s4028600 iT邦新手 5 級 ‧ 2019-12-30 20:08:47 檢舉

了解了

2
小魚
iT邦大師 1 級 ‧ 2019-12-29 22:42:24

try / catch ?

看更多先前的回應...收起先前的回應...
s4028600 iT邦新手 5 級 ‧ 2019-12-29 23:01:16 檢舉

什麼意思
那裡是指當圖片讀取失敗就打印路徑並刪除
但是現在不知道為什麼無法刪除了

ccutmis iT邦高手 2 級 ‧ 2019-12-29 23:13:28 檢舉

#os.remove(pic_file)#刪除檔案
上面這行 #os.rmove(...) 開頭是#就是整列註解了怎麼會執行?
改成下列這樣就會執行
os.remove(pic_file)#刪除檔案

小魚 iT邦大師 1 級 ‧ 2019-12-29 23:14:49 檢舉

所以有抓到什麼錯誤訊息嗎?

ccutmis iT邦高手 2 級 ‧ 2019-12-29 23:23:06 檢舉

不確定 只知道他把應該要刪除檔案的那一刪註解掉了
Python裡面井字號在最左側跟 JS的 //是一樣的意思

小魚 iT邦大師 1 級 ‧ 2019-12-29 23:57:07 檢舉

我懂你的意思了,
你是要檢查圖片能不能正常載入,
如果不能就刪掉,
但是你將刪除檔案那行註解,
那怎麼可能執行呢?

s4028600 iT邦新手 5 級 ‧ 2019-12-30 00:01:41 檢舉

註解是測試時避免誤刪
在測試刪除功能時是會刪除#的

D:\long\Desktop\test\image (2).jpg
Traceback (most recent call last):
  File "D:\long\Desktop\test\8.py", line 42, in <module>
    img.load()
  File "C:\Users\long\AppData\Local\Programs\Python\Python36\lib\site-packages\PIL\ImageFile.py", line 249, in load
    "(%d bytes not processed)" % len(b)
OSError: image file is truncated (79 bytes not processed)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\long\Desktop\test\8.py", line 47, in <module>
    os.remove(pic_file)#刪除檔案
PermissionError: [WinError 32] 程序無法存取檔案,因為檔案正由另一個程序使用。: 'D:\\long\\Desktop\\test\\image (2).jpg'

他指的另一個程序就是他自己
但我不懂為什麼之前沒這個問題

1
舜~
iT邦高手 1 級 ‧ 2019-12-29 23:51:21

假設您的程式沒錯
那麼...

檔案/資料夾 有權限進行刪除嗎?
路徑有變嗎?
軟體設定的檔案副檔名一樣是 png或jpg ?

s4028600 iT邦新手 5 級 ‧ 2019-12-30 00:04:13 檢舉

可以正常刪除
但是這代碼不知道問題出在哪不會刪除
路徑沒變是正常的
軟體設定?
路徑沒變啊?

我要發表回答

立即登入回答