cur_path = os.path.dirname(os.path.realpath(sys.argv[0]))
print(f'cur_path = {cur_path}')
os.chdir(cur_path) # 变更当前工作目录
print(f'os.path = {os.path}')
print(f'os.getcwd() = {os.getcwd()}')
后续代码就可以使用当前工作目录下的相对路径了。
当然也可以把第一行获取的 cur_path 用 os.path.join 和相对路径连接起来,组成绝对路径来操作。如果程序始终使用绝对路径的时候,就不需要 通过 os.chdir 来变更当前工作路径了。
注意:其他方式,例如 Path(__file__).parent.absolute() 或 os.path.abspath(__file__) 看起来也可以获取到脚本所在目录,但是一旦编译成为单exe文件运行时,就会发现此时执行使用的工作目录不是 exe 文件所在目录!很坑!