首页 > 解决方案 > Python 当前工作目录设置为主路径而不是脚本目录

问题描述

执行以下脚本时,为什么没有将 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 文件,右键单击输出C:/Python27/python.exe c:/Users/user/Desktop/test.py命令的“在终端中执行 python 文件”。

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

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

标签: pythonjsonpython-2.7visual-studio-code

解决方案


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


推荐阅读