看板 Python 關於我們 聯絡資訊
import imghdr import os root=["D:\long\Desktop"] for path in root: for dirPath, dirNames, fileNames in os.walk(path): for file in fileNames: pic_file=os.path.join(dirPath,file) img = imghdr.what(pic_file) #print(os.path.splitext(pic_file)[1]) if os.path.splitext(pic_file)[1].lstrip('.') != img: #print(img,pic_file) #print(os.path.splitext(pic_file)[0]) name=os.path.splitext(pic_file)[0]+'.'+img print(name) os.rename(pic_file,name) 有幾個問題 1.我所用的imghdr似乎只能辨認圖片的副檔名 它把我的txt當錯誤的檔案 有能辨識其他副檔名是否正確的包嗎 2.我用其他程式辨識的是jpg但是imghdr的辨識卻是jpeg 3.遇到非圖片的會錯誤比如txt 不過有打算用try所以算是小問題 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.170.107.223 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1574951346.A.0EC.html
AndCycle: 那個, jpg 是因為副檔名3個字這個慣例所產生的簡寫 ...11/28 22:39
s4028600: 了解那2.的解決方法就設定其他條件好了11/28 23:29
s4028600: 1和3有方法嗎11/28 23:29
ZongXiu: 有試過 字串[-4:]=='.jpg' ?11/29 09:28
問題2的確打算用類似這種方法解決
TuCH: 改字串為什麼要用imghdr阿阿阿11/29 09:31
為了辨識檔案副檔名是否正確啊... 有沒有其他能辨識的嗎
TuCH: 副檔名就是.split('.')[-1]吧11/29 09:33
或許可以改良看看 但是我還在頭痛問題1、3
s860134: 其實有 os.path 就有 os.path.splitext11/29 12:49
這是回答上一樓的嗎? 我的確是用這種方式來定位副檔名 ※ 編輯: s4028600 (125.224.162.184 臺灣), 11/29/2019 18:55:09 找到一個可以用的包了 一口氣解決1、2、3的問題 用TuCH方法縮短一點長度 import filetype import os root=[input("輸入路徑:")] for path in root: for dirPath, dirNames, fileNames in os.walk(path): for file in fileNames: pic_file=os.path.join(dirPath,file) kind = filetype.guess(pic_file) if kind is None: pass #print('Cannot guess file type!') else: #print(kind.extension) #print('File extension: %s' % kind.extension) #print('File MIME type: %s' % kind.mime) if pic_file.split('.')[-1] != kind.extension: name=pic_file.split('.')[0]+'.'+kind.extension print(pic_file) print(name) #print(pic_file.split('.')[-1]) os.rename(pic_file,name) ※ 編輯: s4028600 (125.224.162.184 臺灣), 11/30/2019 03:06:44
s4028600: 手機要用整頁或瀏覽器才是正常的縮排 11/30 03:08
s4028600: 感謝各位建議 11/30 03:10
MARGHT: 還有pathlib可以用 12/01 13:44
s4028600: 感謝 可惜沒相關教學 好像沒辦法用 12/05 04:16
max533: pathlib(限python3)推推,處理檔案以物件導向型式很方便 12/11 08:26