Advertisement
Guest User

Randomly Draw Players.py

a guest
Oct 4th, 2014
263
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.60 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. # Python 3
  3.  
  4. # Randomly Draw Players
  5.  
  6. import sys
  7. import pathlib
  8. import random
  9.  
  10. if len(sys.argv) < 2:
  11.     raise Exception("Missing argument: input_file_name")
  12.  
  13. script_file_name = sys.argv[0]
  14. input_file_path = pathlib.Path(sys.argv[1])
  15.  
  16. with open(file=str(input_file_path.absolute()),
  17.     mode='r',
  18.     buffering=-1,
  19.     encoding='utf-8'
  20. ) as input_file: # {
  21.  
  22.     players_dict = dict()
  23.     input_file.lineno = 0
  24.  
  25.     for input_line in input_file: # {
  26.         input_file.lineno += 1
  27.         try:
  28.             player_name, player_id = input_line.strip().split('\t')
  29.         except ValueError:
  30.             raise Exception("File error {!r} at line {}!".format( input_file_path.name, input_file.lineno ))
  31.         else:
  32.             players_dict.update({player_name: player_id})
  33.     # }
  34.  
  35. # } with open
  36.  
  37. if not len(players_dict):
  38.     raise Exception("Missing players")
  39.  
  40. output_file_path = input_file_path
  41.  
  42. i = 0
  43. while output_file_path.exists(): # { Find an no-existing file name
  44.     i += 1
  45.     output_file_path = pathlib.Path( # Folder + name_base + name_extension
  46.         input_file_path.parent,
  47.         input_file_path.stem + " output {}".format(i) + input_file_path.suffix
  48.     )
  49. # }
  50.  
  51. with open(file=str(output_file_path.absolute()),
  52.     mode='w',
  53.     buffering=-1,
  54.     encoding='utf-8'
  55. ) as output_file: # {
  56.  
  57.     while len(players_dict): # { Extract randomly each players
  58.         player_chosen_name = random.choice(list(players_dict.keys())) # Choose randomly a player name
  59.         player_chosen_id = players_dict.pop(player_chosen_name) # Extract and remove from dictionary
  60.         output_file.writelines( "{}\t{}\n".format(player_chosen_name, player_chosen_id) )
  61.     # }
  62.  
  63. # } with open
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement