2

So I have a python program that writes prime numbers into a csv file. I now want my python file to make a copy of itself after it runs everything, as a backup for when I tweak around with the original file.

I've gotten away with not knowing this so far by making the python program make a new .py file and then writing everything inside it, but this is super inefficient. I'd like it to be cleaner and less complicated.

I've heard a little bit about using shutil.copyfile, but I'm not too sure about how to use it. Is shutil.copyfile the best way to make my python file copy itself, or is there a better way?

Alexander Kalian
  • 1,059
  • 2
  • 9
  • 17
  • 1
    Take a look at `Git` http://en.wikipedia.org/wiki/Git_%28software%29 – Vor Aug 27 '14 at 16:25
  • Have you tried `shutil.copy(__file__, "destination.py")`? –  Aug 27 '14 at 16:26
  • Don't make your program copy itself. Use a real backup strategy, or even better, a version control system like Git, as @Vor suggested. – Ned Batchelder Aug 27 '14 at 16:38
  • _as a backup_ - one of the problems you'll encounter is that unless you generate a unique name for the program on every copy, a run will overwrite previous runs, which kinda defeats the purpose of having a backup. – tdelaney Aug 27 '14 at 16:45

1 Answers1

2

Revision control software is meant to solve this problem, that is, keeping a copy of your old files. Doing it your way will make your source folder really cluttered. Mercurial/Hg is really easy to learn and use (its also written in python).

Otherwise to answer the question:

shutil.copy(__file__, "new_destination.py")
vikki
  • 2,766
  • 1
  • 20
  • 26
  • You don't need abspath, but the bigger problem is that `__file__` is likely the .pyc file. You'll want to trim that to get the .py file. – tdelaney Aug 27 '14 at 16:43
  • @tdelaney that depends on your current working directory. If you are inside the path the file is located it will only return a relative path to the .py file. See http://stackoverflow.com/questions/7116889/python-file-attribute-absolute-or-relative –  Aug 27 '14 at 16:47
  • @Thimble - you are correct that the file name is not always absolute. But you don't need absolute file names to copy files. – tdelaney Aug 27 '14 at 16:56
  • 1
    @tdelaney you're right about not needing the abspath. About needing to trim `.pyc`, unless the file is imported as a module and being copied like `module.__file__`, the likelihood is higher that `__file__` will return a `.py` path because the script is being run directly, i.e `python script.py`. The path would end with `.pyc` if OP runs the `.pyc` directly. – vikki Aug 27 '14 at 17:11
  • @vikki - okay, I'll change that to "its possible" instead of "likely". – tdelaney Aug 27 '14 at 17:19
  • Everyone is right I will use better methods for backing things up, but this answer is correct and I will probably need to use it to automatically copy files one day. – Alexander Kalian Aug 27 '14 at 17:58