歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

Python打印當前目錄下的圖片文件

Python打印當前目錄下的圖片文件,源代碼參考_Python_cookbook
代碼如下: 

  1. import os, itertools
  2. def anyTrue(predicate,sequence):
  3.     return True in itertools.imap(predicate,sequence)

  4. def endsWith(s,*endings):
  5.     return anyTrue(s.endswith,endings)
  6. '''
  7. s.endswith 是一個方法,判斷後綴名是否是在指定的endings裡,如果是返回True
  8. anyTrue(s.endswith,endings) 將這個方法傳遞給anyTrue,
  9. itertools.imap(predicate,sequence) 就相當於filename.endswith(enddings)
  10. 返回結果為True就執行print filename
  11. '''

  12. for filename in os.listdir('.'):
  13.     if endsWith(filename,'.jpg','.jpeg','.gif'):
  14.         print filename

endswith判斷文件後綴名是否在列表當中 

  1. str.endswith(suffix[, start[, end]])
  2. 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.


  3. Example:

  4. #!/usr/bin/python

  5. str = "this is string example....wow!!!";

  6. suffix = "wow!!!";
  7. print str.endswith(suffix);
  8. print str.endswith(suffix,20);

  9. suffix = "is";
  10. print str.endswith(suffix, 2, 4);
  11. print str.endswith(suffix, 2, 6);
  12. This will produce following result:

  13. True
  14. True
  15. True
  16. False
Copyright © Linux教程網 All Rights Reserved