Json IOError:[Errno 2]没有这样的文件或目录:使用python在windows中使用os.path.dirname和os.path.join

Json IOError:[Errno 2]没有这样的文件或目录:使用python在windows中使用os.path.dirname和os.path.join,json,python-2.7,Json,Python 2.7,我想使用以下代码读取文件: import os DIRNAME = os.path.dirname(__file__) mydir=os.path.join(DIRNAME,'test.json') myfile = open(mydir) # alice.txt is in the same dir as foo.py mytxt = myfile.read() myfile.close() 我有以下错误: IOError: [Errno 2] No such file or direc

我想使用以下代码读取文件:

import os

DIRNAME = os.path.dirname(__file__)
mydir=os.path.join(DIRNAME,'test.json')
myfile = open(mydir)  # alice.txt is in the same dir as foo.py
mytxt = myfile.read()
myfile.close()
我有以下错误:

IOError: [Errno 2] No such file or directory: 'C:/Users/user/Documents/MyTest\\test.json'

我在那个目录中有
test.json
,但我不确定为什么会有这个错误。有什么问题吗?

Python混合了前斜杠和后斜杠。您可以通过替换
DIRNAME
中的前斜杠来解决此问题:

DIRNAME = '\\'.join(os.path.dirname(__file__).split("/"))
mydir=os.path.join(DIRNAME,'test.json')
print mydir
返回:

C:\Users\f3k\Documents\temp\test.json