# python 3.6+importsys,randomdefusage(exit_code=0):print('usage: python3 rand9999.py [FILE]')sys.exit(exit_code)if'-h'insys.argvor'--help'insys.argv:usage()iflen(sys.argv)>2:usage(1)filename=Noneiflen(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')iffilenameelsesys.stdout)asfile:numbers=list(range(10000))random.shuffle(numbers)fornuminnumbers:file.write(f'{num:#04d}\n')
It would have been cleaner to use random.sample like @alonsovb
did.
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.