遍历目录中的图像

looping over images in a directory

我在与 python 文件相同的目录中有图像,我试图遍历图像并将它们转换为 base64,但出现此错误。 我正在使用 Ubuntu 14.0.4

    Traceback (most recent call last):
  File "convert_to_base64.py", line 33, in <module>
    print(main())
  File "convert_to_base64.py", line 26, in main
    convert_to_base64()
  File "convert_to_base64.py", line 19, in convert_to_base64
    with open("*.jpg", "rb") as f:
IOError: [Errno 2] No such file or directory: '*.jpg'

这是我的 python 代码

# -*- coding: utf-8 -*-
import os
import sys
import xlrd
import base64
import urllib
from datetime import datetime

reload(sys)  # to re-enable sys.setdefaultencoding()
sys.setdefaultencoding('utf-8')


def convert_to_base64():
    """
    Read all jpg images in a folder,
    and print them in base64
   """
    with open("*.jpg", "rb") as f:
        data = base64.b64decode(f.read())
    print data


def main():
    start_datetime = datetime.now()
    convert_to_base64()
    end_datetime = datetime.now()
    print '------------------------------------------------------'
    print 'Script started  : {}'.format(start_datetime)
    print 'Script finished: {}'.format(end_datetime)

if __name__ == '__main__':
    print(main())
    print('Done')

有人帮我弄清楚哪里做错了。 谢谢

这是我在目录中循环查找图像的方式:

import os

pictures = []
for file in os.listdir("pictures"):
    if file[-3:].lower() in ["png"]:
        pictures.append(file)

有关 open() 函数的更多信息,请参阅 Python 文档 https://docs.python.org/2/tutorial/inputoutput.html

open() returns a file object, and is most commonly used with two arguments: open(filename, mode).