import psycopg2 import os path = 'D:\photo\' conn = psycopg2.connect(database="****", port='*****', user="***", password="*****", host="202.38.*.*" ) cur = conn.cursor() cur.execute('''truncate table app.xh_image;''') conn.commit() for dirpath,dirnames,filenames in os.walk(path): print(dirpath,dirnames,filenames) for filepath in filenames: file_path = path + '\' + filepath xh = filepath.split('.')[0] print(file_path,xh) with open(file_path,'rb')as img_open: img_buffer = img_open.read() params = psycopg2.Binary(img_buffer) cur.execute('''insert into app.xh_image(xh,image) values('{}',{});'''.format(xh,params)) conn.commit() conn.close()