Small Python tool for cleaning output of pgsql2shp

clean_pgsql2shp_output.py 1.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import os
  2. import sys
  3. # do this if package missing: pip install dbf
  4. import dbf
  5. #TODO: add parameter for path to clean
  6. #TODO: add parameter for additional extensions
  7. # get dir of .py file a.k.a. current path
  8. filepath = os.path.dirname(os.path.abspath(__file__))
  9. # typical SHP file extension which need to be deleted
  10. extensions = ['dbf', 'prj', 'shp', 'shx']
  11. # counter for deleted files
  12. filesDeleted = 0
  13. for file in os.listdir(filepath):
  14. if file.endswith(".dbf"):
  15. # open DBF file with dbf package; assumpation: any dbf file with
  16. # zero content is useless
  17. checkDbf = dbf.Table(file)
  18. checkDbf.open()
  19. # check for empty DBF file
  20. if len(checkDbf) == 0:
  21. # get file name without extension
  22. delFile = file.split('.')[0]
  23. # iterate with the possible extensions of the file name
  24. for i in range(0, len(extensions)):
  25. fileToRemove = ""
  26. fileToRemove = delFile + '.' + extensions[i]
  27. # need to close file before we can delete
  28. checkDbf.close()
  29. try:
  30. os.remove(fileToRemove)
  31. filesDeleted += 1
  32. except:
  33. continue
  34. else:
  35. continue
  36. print "\nDeleted {} files.".format(filesDeleted)