【问题标题】:IOError: [Errno 2] No such file or directory: with os.path.dirname and os.path.join in windows using pythonIOError: [Errno 2] No such file or directory: with os.path.dirname and os.path.join in windows using python
【发布时间】:2018-06-10 21:13:30
【问题描述】:

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

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 json python-2.7


    【解决方案1】:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-28
      • 2015-10-20
      • 2016-06-07
      • 1970-01-01
      • 2012-08-25
      相关资源
      最近更新 更多