Python-本地

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python-本地相关的知识,希望对你有一定的参考价值。

  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...'

以上是关于Python-本地的主要内容,如果未能解决你的问题,请参考以下文章

Python本地安装numpy包

python中关于本地文件的API

Python-本地

如何使用 Python 读取本地存储?

Python 本地线程

python获取本地ip的方法