FileNotFoundError但文件存在

时间:2018-11-18 19:00:46

标签: python json python-3.x filenotfoundexception

我正在创建一个导入许多JSON文件的Python应用程序。这些文件与python脚本的位置在同一文件夹中。在将整个文件夹移到其他位置之前,文件已完美导入。由于脚本会创建文件(如果不存在),因此它将继续在主目录中创建文件,而忽略其所在目录中的文件。当我指定绝对路径时(以下代码):

startT= time()
    with open('~/Documents/CincoMinutos-master/settings.json', 'a+') as f:
        f.seek(0,0) # places pointer at start of file
        corrupted = False
        try:
            # turns all json info into vars with load
            self.s_settings = json.load(f)
            self.s_allVerbs = []
            # --- OFFLINE MODE INIT ---
            if self.s_settings['Offline Mode']: # conjugation file reading only happens if setting is on
                with open('~/Documents/CincoMinutos-master/verbconjugations.json', 'r+', encoding='utf-8') as f2: 
                    self.s_allVerbs = [json.loads(line) for line in f2]
            # --- END OFFLINE MODE INIT ---
            for key in self.s_settings:
                if not isinstance(self.s_settings[key], type(self.s_defaultSettings[key])): corrupted = True
        except Exception as e: # if any unexpected error occurs
            corrupted = True
            print('File is corrupted!\n',e)
        if corrupted or not len(self.s_settings):
            f.truncate(0) # if there are any errors, reset & recreate the file
            json.dump(self.s_defaultSettings, f, indent=2, ensure_ascii=False)
            self.s_settings = {key: self.s_defaultSettings[key] for key in self.s_defaultSettings}
    # --- END FILE & SETTINGS VAR INIT ---
    print("Finished loading file in {:4f} seconds".format(time()-startT))

它吐出FileNotFound错误。

    Traceback (most recent call last):
  File "/Users/23markusz/Documents/CincoMinutos-master/__main__.py", line 709, in <module>
    frame = CincoMinutos(root)
  File "/Users/23markusz/Documents/CincoMinutos-master/__main__.py", line 42, in __init__
    with open('~/Documents/CincoMinutos-master/settings.json', 'a+') as f:
FileNotFoundError: [Errno 2] No such file or directory: '~/Documents/CincoMinutos-master/settings.json'

请记住,从终端操作时,我完全可以使用相同的绝对路径来访问它。有人可以解释一下我需要做什么才能正确导入文件吗?

此外,我正在为多个用户创建此应用程序。尽管/Users/23markusz/Documents/CincoMinutos-master/verbconjugations.json可以正常工作,但是不会在其他用户的系统上运行。该文件也作为脚本位于SAME FOLDER中,因此应正确导入。

更新: 虽然使用os.path.expanduser()解决了我的问题,但我仍然不明白为什么python拒绝打开与python脚本位于同一文件夹中的文件。它应该自动打开仅包含文件名而不是绝对路径的文件。

1 个答案:

答案 0 :(得分:3)

"~"不是真实的目录(并且不符合“绝对路径”的要求),这就是为什么打开不起作用的原因。

为了将波浪号扩展到实际目录(例如/Users/23markusz),可以使用os.path.expanduser

import os
...
with open(os.path.expanduser('~/Documents/CincoMinutos-master/settings.json'), 'a+') as f:
    # Do stuff