Search code examples
pythonpython-3.xrandomreplicate

Python 3 Self replicating file into random directory - then running file


I have a fun little script that i would like to make a copy of itself in a random directory - then run that copy of itself.

I know how to run files with (hacky):

os.system('Filename.py')

And i know how to replicate files with shuttle - but i am stuck at the random directory. Maybe if i could somehow get a list of all directories available and then pick one at random from the list - then remove this directory from the list?

Thanks, Itechmatrix


Solution

  • You can get list of all dirs and subdirs, and shuffle it in random as follows:

    import os
    import random
    
    all_dirs = [x[0] for x in os.walk('/tmp')]
    random.shuffle(all_dirs)
    
    for a_dir in all_dirs:
        print(a_dir)
        # do something witch each directory, e.g. copy some file there.