FileNotFoundError but file exists

旧巷老猫 提交于 2021-02-16 15:33:02

问题


I am creating a Python application that imports many JSON files. The files are in the same folder as the python script's location. Before I moved the entire folder someplace else, the files imported perfectly. Since the script creates a files if none exists, it keeps creating the file in the home directory while ignoring the one in the same folder as it is in. When I specify an absolute path (code below):

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))

It spits out a FileNotFound error.

    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'

Keep in mind that I am perfectly able to access it with the same absolute path when I operate from terminal. Can somebody please explain what I need to do in order for the files to import correctly?

Also, I am creating this application for multiple users. While /Users/23markusz/Documents/CincoMinutos-master/verbconjugations.json does work, it will not on another user's system. This file is also in the SAME FOLDER as the script so it should import correctly.

UPDATE: While my issue is solved using os.path.expanduser(), I still do not understand why python refuses to open a file that is within the same folder as the python script. It should automatically open the file with just the filename and not the absolute path.


回答1:


"~" isn't a real directory (and would not qualify as an "absolute path"), and that's why the open doesn't work.

In order to expand the tilde to an actual directory (e.g. /Users/23markusz), you can use os.path.expanduser:

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


来源:https://stackoverflow.com/questions/53364429/filenotfounderror-but-file-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!