Python打印當前目錄下的圖片文件,源代碼參考_Python_cookbook
代碼如下:
- import os, itertools
- def anyTrue(predicate,sequence):
- return True in itertools.imap(predicate,sequence)
- def endsWith(s,*endings):
- return anyTrue(s.endswith,endings)
- '''
- s.endswith 是一個方法,判斷後綴名是否是在指定的endings裡,如果是返回True
- anyTrue(s.endswith,endings) 將這個方法傳遞給anyTrue,
- itertools.imap(predicate,sequence) 就相當於filename.endswith(enddings)
- 返回結果為True就執行print filename
- '''
- for filename in os.listdir('.'):
- if endsWith(filename,'.jpg','.jpeg','.gif'):
- print filename
endswith判斷文件後綴名是否在列表當中
- str.endswith(suffix[, start[, end]])
- Return True if the string ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position.
- Example:
- #!/usr/bin/python
- str = "this is string example....wow!!!";
- suffix = "wow!!!";
- print str.endswith(suffix);
- print str.endswith(suffix,20);
- suffix = "is";
- print str.endswith(suffix, 2, 4);
- print str.endswith(suffix, 2, 6);
- This will produce following result:
- True
- True
- True
- False