Home > Python > 根据文件夹下的图片生成网页
07,09,2018 | dengwen168 |
有时我们有这样一个需求:有编号为1-100的文件夹,里面有3-5张缩略图,需要将这些图片发布到网站上,每个文件夹中的图片发布到一张网页上。这时只需要将以下代码稍作修改即可。
本脚本功能为:获取本目录下的pic子目录中的所有图片(jpg,png,bmp,gif等,此处以jpg文件为例),然后生成一个image.html文件,代码如下:
4 |
def showImageInHTML(imageTypes,savedir): |
5 |
files=getAllFiles(savedir+ '\\pic' ) |
6 |
images=[f for f in files if f[f.rfind( '.' )+1:] in imageTypes] |
7 |
images=[item for item in images if os.path.getsize(item)>5*1024] |
8 |
images=[ 'pic' +item[item.rfind( '\\' ):] for item in images] |
9 |
newfile= '%s\\%s' %(savedir, 'images.html' ) |
10 |
with open(newfile, 'w' ) as f: |
13 |
f.write( "<img src='%s'>\n" %image) |
15 |
print ( 'success,images are wrapped up in %s' %newfile) |
17 |
def getAllFiles(directory): |
19 |
for dirpath, dirnames,filenames in os.walk(directory): |
21 |
for file in filenames: |
22 |
files.append(dirpath+ '\\' +file) |
30 |
#判断为脚本文件还是py2exe编译后的文件,如果是脚本文件,则返回的是脚本的目录,如果是py2exe编译后的文件,则返回的是编译后的文件路径 |
31 |
if os.path.isdir(path): |
33 |
elif os.path.isfile(path): |
34 |
return os.path.dirname(path) |
36 |
if __name__ == '__main__' : |
37 |
savedir=cur_file_dir()#获取当前.py脚本文件的文件路径 |
38 |
showImageInHTML(( 'jpg' , 'png' , 'gif' ), savedir)#浏览所有jpg,png,gif |
转载请注明:XAMPP中文组官网 » 根据文件夹下的图片生成网页