re: Write a simple but impactful script VIEW POST

FULL DISCUSSION
 
# python 3.6+
import sys, random

def usage(exit_code=0):
    print('usage: python3 rand9999.py [FILE]')
    sys.exit(exit_code)

if '-h' in sys.argv or '--help' in sys.argv:
    usage()

if len(sys.argv) > 2:
    usage(1)

filename = None
if len(sys.argv) == 2:
    filename = sys.argv[1]

# Feel free to reply if you can think of a cleaner way to do this.
# Putting 'f = open(..) if.. else..' outside the 'with', 
# and then doing "with f as file:" makes it more readable,
# but also seems unsafe, as it could lead to forgetting to
# close files as a general practice.
with (open(filename, 'w') if filename else sys.stdout) as file:
    numbers = list(range(10000))
    random.shuffle(numbers)
    for num in numbers:
        file.write(f'{num:#04d}\n')

It would have been cleaner to use random.sample like @alonsovb did.

Edit: Updated to use random.sample and ArgParse.

Edit2: I made a post about some different ways to do the file_or_stdout thing. Maybe you can think of a better way.

code of conduct - report abuse