[英]How to avoid python running file in the directory where the code is located?
I'm writing a script that will download an executable from the internet, which will create more files.我正在编写一个脚本,该脚本将从 Internet 下载一个可执行文件,这将创建更多文件。 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.
现在,如果我下载文件,它将被下载到我告诉它的目录中,但是当我使用 os.startfile() 打开它时,它会在 python 脚本所在的目录中创建文件。 How can I avoid that?
我怎样才能避免这种情况?
Do a os.chdir()
before trying to run the executable:在尝试运行可执行文件之前执行
os.chdir()
:
os.chdir('<the target folder where you want the files to be created>')
...
os.startfile('<path to where the executable was downloaded>')
Either you can move the .py
file to any other directory.您可以将
.py
文件移动到任何其他目录。 or You can use os.chdir() to change the current working directory of the script during the runtime.或者您可以使用os.chdir()在运行时更改脚本的当前工作目录。
os.chdir('/path/to/directory')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.