[問題] 檢查副檔名並重新命名

看板Python作者 (佑)時間4年前 (2019/11/28 22:29), 4年前編輯推噓4(408)
留言12則, 7人參與, 4年前最新討論串1/1
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

11/28 22:39, 4年前 , 1F
那個, jpg 是因為副檔名3個字這個慣例所產生的簡寫 ...
11/28 22:39, 1F

11/28 23:29, 4年前 , 2F
了解那2.的解決方法就設定其他條件好了
11/28 23:29, 2F

11/28 23:29, 4年前 , 3F
1和3有方法嗎
11/28 23:29, 3F

11/29 09:28, 4年前 , 4F
有試過 字串[-4:]=='.jpg' ?
11/29 09:28, 4F
問題2的確打算用類似這種方法解決

11/29 09:31, 4年前 , 5F
改字串為什麼要用imghdr阿阿阿
11/29 09:31, 5F
為了辨識檔案副檔名是否正確啊... 有沒有其他能辨識的嗎

11/29 09:33, 4年前 , 6F
副檔名就是.split('.')[-1]吧
11/29 09:33, 6F
或許可以改良看看 但是我還在頭痛問題1、3

11/29 12:49, 4年前 , 7F
其實有 os.path 就有 os.path.splitext
11/29 12:49, 7F
這是回答上一樓的嗎? 我的確是用這種方式來定位副檔名 ※ 編輯: 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

11/30 03:08, 4年前 , 8F
手機要用整頁或瀏覽器才是正常的縮排
11/30 03:08, 8F

11/30 03:10, 4年前 , 9F
感謝各位建議
11/30 03:10, 9F

12/01 13:44, 4年前 , 10F
還有pathlib可以用
12/01 13:44, 10F

12/05 04:16, 4年前 , 11F
感謝 可惜沒相關教學 好像沒辦法用
12/05 04:16, 11F

12/11 08:26, 4年前 , 12F
pathlib(限python3)推推,處理檔案以物件導向型式很方便
12/11 08:26, 12F
文章代碼(AID): #1Ttzco3i (Python)