How to avoid python running file in the directory where the code is located?

此生再无相见时 提交于 2021-02-05 11:48:24

问题


I'm writing a script that will download an executable from the internet, which will create more files. Now, if I download the file, it will be downloaded to the directory I told it, but when I open it using os.startfile(), it creates the files to the directory where the python script is located. How can I avoid that?


回答1:


Either you can move the .py file to any other directory. or You can use os.chdir() to change the current working directory of the script during the runtime.

os.chdir('/path/to/directory')



回答2:


Do a os.chdir() before trying to run the executable:

os.chdir('<the target folder where you want the files to be created>')
...
os.startfile('<path to where the executable was downloaded>')


来源:https://stackoverflow.com/questions/64506537/how-to-avoid-python-running-file-in-the-directory-where-the-code-is-located

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