How to set the current working directory in Python?
To set the current working directory, you can use the chdir() function in the os module.
import os
# 获取当前工作路径
current_path = os.getcwd()
print("当前工作路径:", current_path)
# 设置新的工作路径
new_path = "/path/to/new/directory"
os.chdir(new_path)
# 检查新的工作路径
current_path = os.getcwd()
print("新的工作路径:", current_path)
In the example above, the current working directory is first obtained using the os.getcwd() function, then a new working directory is set using the os.chdir() function. Finally, the os.getcwd() function is used again to verify if the setting was successful.