Python - randomLocal


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. import os
  2. import random
  3.  
  4. class localImages(object):
  5.  
  6. def __init__(self, directory='/home/Foto'):
  7.  
  8. self.directoryScan = directory # Cartella da cui cominciare a prelevare le foto
  9. self.directoryRemain = [self.directoryScan]
  10. self.filePath = {}
  11.  
  12. def getRandomImages(self):
  13. '''
  14. Prelieva dal proprio disco delle immagini in maniera random...
  15. '''
  16.  
  17. for i in range(5): # Scansiona 5 directory
  18. if len(self.directoryRemain) > 0:
  19. directory = random.choice(self.directoryRemain)
  20. self.directoryRemain.remove(directory)
  21.  
  22. files = []
  23.  
  24. try:
  25. files = os.listdir(directory)
  26. except:
  27. pass
  28.  
  29. # Serve per aumentare il Random delle Foto
  30. # FIXME: cercare di aumentare questo random
  31. if len(files) > 0:
  32. for i in range(len(files)/2):
  33. files_remove = random.choice(files)
  34. files.remove(files_remove)
  35. ##########################################
  36.  
  37. for filename in files:
  38. filepath = os.path.join(directory, filename)
  39.  
  40. if os.path.isdir(filepath):
  41. self.directoryRemain.append(filepath)
  42. elif os.path.isfile(filepath):
  43. (name, ext) = os.path.splitext(filepath)
  44. if ext.lower() in ('.jpg', '.gif'):
  45. self.filePath[filepath] = 0
  46.  
  47. if len(self.directoryRemain) == 0: self.directoryRemain = [self.directoryScan]
  48.  
  49. def downloadImages(self):
  50. '''
  51. Scarica nella cartella localIMGs le foto che vengono trovate nel disco...
  52. '''
  53.  
  54. numberIMGs = len(self.filePath)
  55. posIMGs = 1
  56.  
  57. for imageName in self.filePath:
  58. print '[' + str(posIMGs) + '/' + str(numberIMGs) + '] - ' + imageName
  59. fread = open(imageName, 'rb')
  60. fwrite = open('localIMGs' + os.sep + os.path.split(imageName)[1], 'wb')
  61. fwrite.write(fread.read())
  62. fread.close()
  63. fwrite.close()
  64. posIMGs += 1
  65.  
  66. if __name__ == '__main__':
  67.  
  68. test = localImages()
  69.  
  70. test.getRandomImages()
  71. test.downloadImages()
  72.  
  73. print 'Finito...'

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.