Akintos

headertool.py

Jan 29th, 2019
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.00 KB | None | 0 0
  1. try:
  2.     from configparser import ConfigParser
  3. except ImportError:
  4.     from ConfigParser import ConfigParser
  5.  
  6. import os
  7. import sys
  8. import shutil
  9. import traceback
  10.  
  11.  
  12. CONFIG_PATH = 'config.ini'
  13.  
  14. DEFAULT_CONFIG = """\
  15. [OPTIONS]
  16. HeaderFile = header.bin
  17. InputFolder = input
  18. OutputFolder = output
  19. """
  20.  
  21. def main():
  22.     if not os.path.isfile(CONFIG_PATH):
  23.         with open(CONFIG_PATH, 'w', encoding='utf8') as c:
  24.             c.write(DEFAULT_CONFIG)
  25.    
  26.     config = ConfigParser()
  27.     config.read(CONFIG_PATH)
  28.  
  29.     header_file = config.get('OPTIONS', 'HeaderFile')
  30.     input_dir = config.get('OPTIONS', 'InputFolder')
  31.     output_dir = config.get('OPTIONS', 'OutputFolder')
  32.    
  33.     if os.path.exists(output_dir):
  34.         shutil.rmtree(output_dir)
  35.  
  36.     os.makedirs(input_dir, exist_ok=True)
  37.     os.makedirs(output_dir, exist_ok=True)
  38.    
  39.     if not os.path.isfile(header_file):
  40.         sys.stderr.write("ERROR: header file '%s' not found." % header_file)
  41.         with open(header_file, 'wb') as h:
  42.             sys.stderr.write(" Created empty file.\n")
  43.         return
  44.  
  45.     with open(header_file, 'rb') as h:
  46.         header_data = h.read()
  47.    
  48.     if len(header_data) == 0:
  49.         sys.stderr.write("ERROR: header file is empty.")
  50.         return
  51.  
  52.     filecount = 0
  53.  
  54.     for path, folders, files in os.walk(input_dir):
  55.         for filename in files:
  56.             fullpath = os.path.join(path, filename)
  57.             relpath = os.path.relpath(fullpath, input_dir)
  58.             outpath = os.path.join(output_dir, relpath)
  59.  
  60.             os.makedirs(os.path.dirname(outpath), exist_ok=True)
  61.  
  62.             with open(fullpath, 'rb') as i, open(outpath, 'wb') as o:
  63.                 o.write(header_data)
  64.                 o.write(i.read())
  65.  
  66.             print(relpath)
  67.             filecount += 1
  68.  
  69.     print("Total %d files" % filecount)
  70.            
  71.  
  72.    
  73. if __name__ == "__main__":
  74.     try:
  75.         main()
  76.     except:
  77.         print(traceback.format_exc())
  78.     finally:
  79.         os.system('pause')
Advertisement
Add Comment
Please, Sign In to add comment