我遇到了图像文件的棘手问题(在 PAW:PythonAnywhere)。 在编码从图像文件中提取元数据时,我成功使用了其中一些,而另一些则声称不存在,或者不是文件。
但是,所有 jpg 文件对于我的代码处理来说都是等效的:
import os, os.path
import iptcinfo3
from pathlib import Path
for fname in os.listdir('static/ImagesCabWillA'):
fil1=Path(fname)
if not fil1.exists():
print(fname, " doesn't exist")
print("§"*15)
for fname in os.listdir('static/ImagesCabWillA'):
if os.path.isfile(fname):
print('ok ', fname, 'type : ', type(fname))
else:
print('NOT ok : ',fname, 'type : ', type(fname))
print('==== end list1 ====')
for fname in os.listdir('static/ImagesCabWillA'):
if os.path.isfile(fname) and fname.split(".")[1] in ("jpg","jpeg","JPG","JPEG"):
print("\n",fname,"\n")
info = iptcinfo3.IPTCInfo(fname, force=True)
print('-----------')
print(info)
# python what is b prefix in string printing : byte, byte string
print (type(info["headline"]))
print('=============') # <class 'bytes'>
# if isinstance(info['object name'],bytes):
print('zzzzzzzzz')
print(info["headline"].decode("utf-8")) # , "\n"
print(info["object name"].decode("utf-8"), "\n" )
我在谷歌上调查了很多,但我没有得到线索:
任何想法都将受到欢迎 我当前的代码,重点调试这个问题: test_iptc3.py
文件夹内容:
01.jpg 2024-03-22 20:33 45.3 KB 02_DSCF0225.JPG 2024-03-22 20:33 525.5 KB 03_IMG-20220517-WA0006.jpeg 2024-03-22 20:33 317.7 KB 04_IMG_20220207_182856.jpg 2024-03-22 20:33 386.8 KB 05_IMG-20220325-WA0014.jpeg 2024-03-22 20:33 201.5 KB 06_IMG-20220517-WA0013.jpeg 2024-03-22 20:33 303.9 KB 07_IMG-20220325-WA0021.jpeg 2024-03-22 20:33 197.9 KB 08_IMG_20220509_193214.jpg 2024-03-22 20:33 430.4 KB 09_DSCF8528.JPG 2024-03-22 20:33 273.1 KB DSCF9384Lite.JPG 2024-04-14 17:42 462.2 KB DSCF9387Lite.JPG 2024-04-14 16:33 496.4 KB
os.listdir()
返回裸名称,而不是完整路径。
如果你这样做
os.listdir('static/ImagesCabWillA'):
,你需要os.path.join
该路径到你在实际路径中获得的名称,即
for name in os.listdir('static/ImagesCabWillA'):
assert os.path.exists(os.path.join('static/ImagesCabWillA', name))
使用
Path.glob()
会更轻松:
for p in pathlib.Path('static/ImagesCabWillA').glob("*.*"):
print(p) # will represent a full path
那么,你可以做
if p.is_file() and p.suffix.lower() in (".jpg", ".jpeg"):
# process this likely-a-jpeg file