Path issues in Python code

1. Change the current working directory of the program through the cd command

import os
print(os.getcwd()) # /home/youngyoung/PythonPrj
path = '/home/youngyoung/PythonPrj/mydemo'
result = os.popen("cd {} && pwd > ./result.txt".format(path))
print(result) # <os._wrap_close object at 0x7f700d8e9790>
## 会在/home/youngyoung/PythonPrj/mydemo目录下创建result.txt文件,内容是/home/youngyoung/PythonPrj/mydemo
print(os.getcwd()) # /home/youngyoung/PythonPrj

It can be seen that os.popen will create a child process, and the path can only be switched in the child process through the cd command. After the child process ends, the path in the main process has not changed (verified by the os.getcwd() method).

2. Change the current working directory of the program through os.chdir()

import os
os.popen('pwd > ./result.txt')
## 会在/home/youngyoung/PythonPrj目录下创建result.txt文件,内容是/home/youngyoung/PythonPrj,是当前工作目录,即执行Python脚本时所在的工作目录
## 比如在命令行执行方式 PythonPrj]$ /bin/python3 /home/youngyoung/PythonPrj/mydemo/demo01.py
import os
print(os.getcwd()) # /home/youngyoung/PythonPrj
os.chdir('/home/youngyoung/PythonPrj/mytest')
print(os.getcwd()) # /home/youngyoung/PythonPrj/mytest
os.popen("pwd > ./result.txt")
print(os.getcwd()) # /home/youngyoung/PythonPrj/mytest

It can be seen that os.chdir() will change the current working directory of the program.

3. __file__ is the path of the executable script file

print(__file__) # /home/youngyoung/PythonPrj/mydemo/demo01.py,是执行的脚本文件

Guess you like

Origin blog.csdn.net/m0_46829545/article/details/129675804