其實幫人實做不是一個好做法,除非對方己經束手無策。不過我感覺你很不用心,同樣的問題回了又問,還說別人的code沒解決你的問題。這是當然的啊。每個人需求不同,至少他解決了他的問題還分享給你。
我也是初學者,只是剛開始這個問題我是用HEX Editor 去研究了檔案的 binary code,對照檔案本身的解碼表一個個去解碼。透過這個過程也學到了很多不同的方法和函式。如果對我有幫助的,我就當練習自己實做了一次。
以下綜整這些日子以來所有的技巧。除了jpg和png外的圖檔不檢查視為正常。格式與副檔名不符的直接修改。提供有類似問題的朋友參考。
import os
import shutil
from PIL import Image
import imghdr
def is_img_valid(imgFile):
isValid = True
try:
Image.open(imgFile).verify()
except:
isValid = False
return isValid
def is_valid_jpg_or_png(imgFile):
if currentFile.endswith('jpeg') or currentFile.endswith('jpg'):
try:
with open(imgFile, 'rb') as f:
f.seek(-2, 2)
return f.read() == b'\xff\xd9'
except OSError:
return False
elif currentFile.endswith('png'):
try:
with open(imgFile, 'rb') as f:
f.seek(-3, 2)
return f.read() == b'\x60\x82\x00' or f.read() [1:] == b'\x60\x82'
except OSError:
return False
else:
return True
rootDirLists = ['Z://folder1', 'C://folder2', 'D://folder3']
count=0
corruptList =[]
formatIncorrect = []
for rootDir in rootDirLists:
print('============尋找目錄 {} 中的圖檔 ============: '.format(rootDir))
for root, dirs, files in os.walk(rootDir):
for file in files:
count += 1
currentFile = os.path.join(root, file).lower()
imgFormat = imghdr.what(currentFile)
if imgFormat != None:
print("檢查第{}個檔案中...檔名為:[{}], 檔頭格式為 [{}], ".format(count, currentFile, imgFormat), end="")
if not is_img_valid(currentFile):
corruptList.append(currentFile)
result = "看來是壞了"
else:
fileExt = currentFile.split('.')[-1]
if fileExt[0:2] not in imgFormat:
formatIncorrect.append(currentFile)
correctedFile = currentFile.replace(currentFile.split('.
print("副檔名與檔頭格式不符, 直接更改檔案名稱為: [{}], "
os.rename(currentFile, correctedFile)
currentFile = correctedFile
if is_valid_jpg_or_png(currentFile):
result = "看起來沒問題"
else:
corruptList.append(currentFile)
result = "看來是壞了"
print(" 檢查結果 [{}]".format(result))
print("============結果 [目錄={}] == [檢查檔案數={}] ============ ".format(rootD
if corruptList:
print('列出壞掉的檔案:')
for i in range(0, len(corruptList)):
print(corruptList[i])
else:
print('沒有壞掉的檔案.')
——-
請看圖以免格式跑掉了
https://i.imgur.com/dmPruPn.jpg
https://i.imgur.com/Ri7f793.jpg
※ 引述《alvinlin (艾爾文)》之銘言:
: hi, 我想說應該不會再有問題了.
: 不知你有試了我寄給你的那個連結的範例了嗎? [後刪]
: ※ 引述《s4028600 (佑)》之銘言:
: : 簡單來說
: : 我已經用os.walk列出所有子資料夾的路徑
: : 然後當作參數進行讀取
: : 但是讀取卻只會讀取列出來的最後一條
: : 我要如何讓他讀取下一個路徑
: : 有相關的教學嗎
: : 網路上只有找到列出路徑
: : 找不到將這些列出的路徑拿來用的方法
: : 求詳細...