问题
Hi my name is Oscar and I would like some help! So the scenario I have is that I am trying to write a python code that will copy itself and put that copy in another directory. I know that you can use the shutil command. For example:
import shutil shutil.copy("C:\Users\%user%\Downloads\file.txt", "C:\Users\%user%\Documents")
But I want to just copy the file so that the script works on any computer that it is located on, for example:
import shutil shutil.copy("file.txt", "C:\Users\%user%\Documents")
If you don't understand what I mean please ask and I can try to elaborate.
Sincerely, Oscar :)
EDIT: I am super dumb it seems like, I did not know that you had to type the destination folder with to backslashes sometimes to actually make it a path. All solved, sorry for wasting everyone's time.
回答1:
You could use pythons standard "os" library to make OS independent filepaths. Then you use the special "file" variable available inside any executed script to get the location of the executed script, to copy itself to some target location. Good luck!
回答2:
The filename of a python file is available using:
import sys
print(sys.argv[0])
You can use this filename to copy the same file elsewhere.
回答3:
I am super dumb it seems like, I did not know that you had to type the destination folder with to backslashes sometimes to actually make it a path. All solved, sorry for wasting everyone's time.
来源:https://stackoverflow.com/questions/53109247/python-copying-a-file-from-an-unknown-destination