I am using python for scientific applications. I run simulations with various parameters, my script outputs the data to an appropriate directory for that parameter set. Later I use that data. However sometimes I edit my script; in order to be able to reproduce my results if needed I would like to have a copy of whatever version of the script was used to generate the data live right in the directory with the data. So basically I would like to have my python script copy itself to the data directory. What's the best way to do this?
Thanks!
I stumbled across this question as I wanted to do the same thing. Although I agree with the comments that git/VCS with revision and everything would be the cleanest solution, sometimes you just want something quick and dirty that does the job. So if anyone is still interested:
With __file__
you can access the running scripts filename (with path), and as already suggested you can use a high-level file manipulation lib like shutil
to copy it to some place. In one line:
shutil.copy(__file__, 'experiment_folder_path/copied_script_name.py')
With the corresponding imports and some bells and whistles:
import shutil
import os # optional: for extracting basename / creating new filepath
import time # optional: for appending time string to copied script# generate filename with timestring
copied_script_name = time.strftime("%Y-%m-%d_%H%M") + '_' + os.path.basename(__file__)# copy script
shutil.copy(__file__, 'my_experiment_folder_path' + os.sep + copied_script_name)