source.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import os
  2. import zipfile
  3. def walk_directory(path, endpoint='.py'):
  4. """
  5. Args:
  6. path: Directory path
  7. endpoint:
  8. Returns: The list of all files' path in the directory
  9. """
  10. file_list = []
  11. for root, dirs, files in os.walk(path):
  12. for file in files:
  13. file_path = os.path.join(root, file)
  14. if file_path.endswith(endpoint):
  15. file_list.append(file_path)
  16. return file_list
  17. def get_file_list(source, endpoint='.py'):
  18. """
  19. Args:
  20. endpoint:file_name's endswith
  21. source:file_name which can be directory, file, zip
  22. Returns:
  23. """
  24. if isinstance(source, str):
  25. if os.path.isdir(source):
  26. return source, walk_directory(source)
  27. elif source.endswith('.py'):
  28. return os.path.dirname(source), [source]
  29. elif source.endswith(('.zip', '.rar', '.7z')):
  30. file_zip = zipfile.ZipFile(source, 'r', zipfile.ZIP_DEFLATED)
  31. py_files = [py_file for py_file in file_zip.namelist() if py_file.endswith(endpoint)]
  32. file_zip.extractall(path=os.path.dirname(source), members=py_files)
  33. return source.replace('.zip', '').replace('.rar', '').replace('.7z', ''), [os.path.dirname(source) + "/" + py_file for py_file in py_files]
  34. # TODO Add the situation that source is a url or a cache
  35. else:
  36. raise ValueError("The parameter source is not supported")
  37. if __name__ == '__main__':
  38. source, file_list = get_file_list("/Users/liufan/program/PYTHON/SAP/TestProject/22-photohash-master.zip")
  39. print(source)
  40. print(file_list)