首页 > 解决方案 > Python:OSError:无法识别图像文件

问题描述

我正在尝试在 Ubuntu 上运行 Python3,但遇到了一些奇怪的错误。该脚本显然无法找到我已确认存在的文件。

这是错误

Traceback (most recent call last):
  File "script.py", line 52, in <module>
    insert_text("For kunde",dir + "/" + project_num + "_signature_customer.jpg", 0)
  File "script.py", line 46, in insert_text
    insert_text(search_term, img_path, (i + 50))
  File "script.py", line 46, in insert_text
    insert_text(search_term, img_path, (i + 50))
  File "script.py", line 40, in insert_text
    img = openpyxl.drawing.image.Image(img_path)
  File "/usr/local/lib/python3.5/dist-packages/openpyxl/drawing/image.py", line 34, in __init__
    image = _import_image(img)
  File "/usr/local/lib/python3.5/dist-packages/openpyxl/drawing/image.py", line 18, in _import_image
    img = PILImage.open(img)
  File "/usr/lib/python3/dist-packages/PIL/Image.py", line 2295, in open
    % (filename if filename else fp))
OSError: cannot identify image file '/var/www/my_ip/uploads/333333_signature_customer.jpg'

这是脚本的一部分

project_num = "333333"
dir = os.path.dirname(os.path.realpath(__file__))

# This function places the image found at img_path 2 cells above where the search_term is found.
def insert_text(search_term, img_path, i):

  if i > 400:
    return None

  found = False

  for x in range(1 + i,51 + i):
    for y in range(1,101):
      if isinstance(ws.cell(row=x, column=y).value,str):
        if  ws.cell(row=x, column=y).value == search_term:
          img = openpyxl.drawing.image.Image(img_path)
          img.anchor = ws.cell(row=(x-2),column=y).coordinate
          ws.add_image(img)
          found = True

  if not found:
    insert_text(search_term, img_path, (i + 50))

# if os.path.isfile(dir + "/" + project_num + "_signature_ikm.jpg"):
  # insert_text("redacted Testing AS",dir + "/" + project_num + "_signature_ikm.jpg", 0)
if os.path.isfile(dir + "/" + project_num + "_signature_customer.jpg"):
  # insert_text("For kunde","signature_customer.jpg", 0)
  insert_text("For kunde",dir + "/" + project_num + "_signature_customer.jpg", 0)

这是我在图像所在的文件夹中使用 LS 命令

john_doe@1e19udt0shu6:/var/www/my_ip/uploads$ ls
333333.xlsx                    333333_signed.xlsx  node_modules       script.py       script_backup.py        signature_redacted.jpg
333333_signature_customer.jpg  redacted2.png            package-lock.json  script.py.save  signature_customer.jpg  test.py

该文件显然在那里,但 Python3 似乎不同意。为什么有任何想法?在调用 insert_text() 之前,我什至确认该文件存在。

标签: pythonpython-3.xubuntuubuntu-16.04

解决方案


文件在那里。只是PIL无法识别图像文件的格式,因此无法加载文件。该文件不是 JPEG 或 PIL 可以加载的任何其他格式。

file 333333_signature_customer.jpg

或者看看它的头

xxd 333333_signature_customer.jpg | head

以确定它实际上是什么类型的文件。(xxdvim包装内)


推荐阅读