循环遍历目录中的图像

时间:2017-09-05 13:46:29

标签: linux python-2.7 base64 ubuntu-14.04

我在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')
有人帮我弄清楚做错了什么。 感谢

1 个答案:

答案 0 :(得分:1)

这是我在目录中循环播放图像的方式:

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()返回一个文件对象,最常用的有两个参数:open(filename,mode)。