【问题标题】:Python current working directoy set to home path instead of script dirPython 当前工作目录设置为主路径而不是脚本目录
【发布时间】:2023-10-06 06:32:01
【问题描述】:

执行以下脚本时,为什么我没有将 json 文件写入当前工作目录(脚本位置)的磁盘?不应该 dump() 这样做吗?

def getShotFolders():
    shotDict = {
        "root" : shotExample,
        "shot_subdirs" : []
    }  
    for root, dirs, files in os.walk(shotExample, topdown=False):
        if root != shotExample:
            shotDict["shot_subdirs"].append(os.path.relpath(root,shotExample))

    pprint(shotDict)
    with open("shot_folderStructure.json", "w") as write_file: 
        json.dump(shotDict, write_file )

getShotFolders()

编辑:好的,我从 vscode 运行我的 python 文件,右键单击“在终端中执行 python 文件”,输出 C:/Python27/python.exe c:/Users/user/Desktop/test.py 命令。

如果我使用与项目解释器相同的 python 集从 pycharm 运行脚本,则会创建 json 文件,但为什么呢?

EDIT2:由于某种原因,当我执行脚本时,cwd 是我的主文件夹,它不应该是 python 脚本的路径。我知道这可以通过os.chdir(os.path.dirname(__file__)) 解决,但不应该这样吧?

【问题讨论】:

    标签: python json python-2.7 visual-studio-code


    【解决方案1】:

    确保您在 VS Code 中打开 C:\Users\user\Desktop 文件夹,以便将 cwd 设置为桌面(如果您直接打开文件,则不会更改您的工作目录)。

    【讨论】: