2017-09-05 145 views
0

我在同一個目錄下有一個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

這是我在一個目錄循環的圖片:

import os 

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

請參考Python文檔https://docs.python.org/2/tutorial/inputoutput.html更多信息有關open()函數:

open()返回一個文件對象,最常用於兩個參數:open(文件名,模式)。