[問題] 檢查副檔名並重新命名
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
11/28 22:39, 1F
→
11/28 23:29,
4年前
, 2F
11/28 23:29, 2F
→
11/28 23:29,
4年前
, 3F
11/28 23:29, 3F
推
11/29 09:28,
4年前
, 4F
11/29 09:28, 4F
問題2的確打算用類似這種方法解決
推
11/29 09:31,
4年前
, 5F
11/29 09:31, 5F
為了辨識檔案副檔名是否正確啊...
有沒有其他能辨識的嗎
→
11/29 09:33,
4年前
, 6F
11/29 09:33, 6F
或許可以改良看看
但是我還在頭痛問題1、3
→
11/29 12:49,
4年前
, 7F
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
12/01 13:44, 10F
→
12/05 04:16,
4年前
, 11F
12/05 04:16, 11F
推
12/11 08:26,
4年前
, 12F
12/11 08:26, 12F