首页 > 解决方案 > os.getcwd() 返回上一级目录

问题描述

我有一个使用当前工作目录的程序。

我正在运行的文件的路径是:/home/pi/Test/file.py

运行 os.getcwd() 时返回的路径是 /home/pi/

我想要的路径是 /home/pi/Test

我错过了什么?

    osDir = os.getcwd()

month = osDir + "/" + month

print (osDir)
print (month)


if not os.path.exists(month):
        os.makedirs(month)

使用 Python3 。

运行文件的命令是 pi@raspberrypi:~ $ python3 TEST/file.py

标签: python

解决方案


os.getcwd()不返回脚本的路径在您的情况下,它返回脚本启动的文件夹的路径/home/pi。如果要获取 python 脚本的绝对路径,请os.path.abspath(os.path.realpath(__file__))改用。

而不是osDir + "/" + month你应该使用os.path.join(osDir, month).


推荐阅读