Advertisement
Foxscotch

file-looping.py (improved)

Oct 21st, 2015
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.51 KB | None | 0 0
  1. import os, re, time, json, pathlib, zipfile
  2.  
  3. path = pathlib.PurePath(os.getcwd())
  4.  
  5. if path.name == 'Blockland' and 'Add-Ons' in os.listdir():
  6.     addon_path = path / 'Add-Ons'
  7. else:
  8.     addon_path = path
  9.  
  10. regex = re.compile(b'\s*function serverCmd([\w\d]+)\s*\(([%\w\d,\s]+)*\)', re.I)
  11. results = {}
  12.  
  13.  
  14. start = time.clock()
  15.  
  16. addon_list = [f for f in os.listdir(str(addon_path)) if f[-3:] == 'zip']
  17.  
  18. for zip_file_name in addon_list:
  19.     zip = zipfile.ZipFile(str(addon_path / zip_file_name))
  20.     file_list = zip.namelist()
  21.     results[zip_file_name[:-4]] = {}
  22.     for file_name in file_list:
  23.         if file_name[-2:] == 'cs':
  24.             file = zip.open(file_name)
  25.             results[zip_file_name[:-4]][file_name[:-3]] = {}
  26.             for line in file:
  27.                 match = regex.match(line)
  28.                 if match:
  29.                     results[zip_file_name[:-4]][file_name[:-3]][match.group(1).decode()] = [m.strip() for m in match.group(2).decode().split(',')]
  30.             if not results[zip_file_name[:-4]][file_name[:-3]]:
  31.                 del results[zip_file_name[:-4]][file_name[:-3]]
  32.             file.close()
  33.     if not results[zip_file_name[:-4]]:
  34.         del results[zip_file_name[:-4]]
  35.     zip.close()
  36.  
  37. end = time.clock()
  38.  
  39. serv_cmd_json = open('server_commands.json', 'w+')
  40. json.dump(results, serv_cmd_json, sort_keys=True, indent=4)
  41. serv_cmd_json.close()
  42.  
  43. print('Results can be found in server_commands.json.')
  44. print('Time taken: {0}'.format(end - start))
  45. input('Press enter to exit.')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement