PYTHON | Copying a file from an unknown destination

不羁岁月 提交于 2021-01-29 07:19:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!