Advertisement
Foxscotch

file-looping.py (+ readable output)

Oct 22nd, 2015
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.17 KB | None | 0 0
  1. import os, re, time, json, pathlib, zipfile
  2.  
  3. # possible output types:
  4. # plain
  5. # json
  6. output_type = 'plain'
  7.  
  8. path = pathlib.PurePath(os.getcwd())
  9.  
  10. if path.name == 'Blockland' and 'Add-Ons' in os.listdir():
  11.     addon_path = path / 'Add-Ons'
  12. else:
  13.     addon_path = path
  14.  
  15. regex = re.compile(b'\s*function serverCmd([\w\d]+)\s*\(([%\w\d,\s]+)*\)', re.I)
  16. results = {}
  17.  
  18.  
  19. start = time.clock()
  20.  
  21. addon_list = [f for f in os.listdir(str(addon_path)) if f[-3:] == 'zip']
  22.  
  23. for zip_file_name in addon_list:
  24.     zip = zipfile.ZipFile(str(addon_path / zip_file_name))
  25.     file_list = zip.namelist()
  26.     results[zip_file_name[:-4]] = {}
  27.     for file_name in file_list:
  28.         if file_name[-2:] == 'cs':
  29.             file = zip.open(file_name)
  30.             results[zip_file_name[:-4]][file_name[:-3]] = {}
  31.             for line in file:
  32.                 match = regex.match(line)
  33.                 if match:
  34.                     results[zip_file_name[:-4]][file_name[:-3]][match.group(1).decode()] = [m.strip() for m in match.group(2).decode().split(',')]
  35.             if not results[zip_file_name[:-4]][file_name[:-3]]:
  36.                 del results[zip_file_name[:-4]][file_name[:-3]]
  37.             file.close()
  38.     if not results[zip_file_name[:-4]]:
  39.         del results[zip_file_name[:-4]]
  40.     zip.close()
  41.  
  42. end = time.clock()
  43.  
  44.  
  45. if output_type == 'plain':
  46.     output_file_name = 'server_commands.txt'
  47.     server_cmd_pl = open(output_file_name, 'w+')
  48.     for addon, script_list in sorted(results.items()):
  49.         if server_cmd_pl.tell() != 0:
  50.             server_cmd_pl.write('\n{0}\n'.format(addon))
  51.         else:
  52.             server_cmd_pl.write('{0}\n'.format(addon))
  53.         for script in script_list.values():
  54.             for command in sorted(script.keys()):
  55.                 server_cmd_pl.write('    {0}\n'.format(command))
  56.     server_cmd_pl.close()
  57. else:
  58.     output_file_name = 'server_commands.json'
  59.     serv_cmd_json = open(output_file_name, 'w+')
  60.     json.dump(results, serv_cmd_json, sort_keys=True, indent=4)
  61.     serv_cmd_json.close()
  62.  
  63. print('Results can be found in {0}.'.format(output_file_name))
  64. print('Time taken: {0}'.format(end - start))
  65. input('Press enter to exit.')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement