FileNotFoundError但文件存在 [英] FileNotFoundError but file exists

查看:329
本文介绍了FileNotFoundError但文件存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个导入许多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脚本位于同一文件夹中的文件.它应该自动打开仅包含文件名而不是绝对路径的文件.

解决方案

"~"不是真实目录(并且不符合绝对路径"的条件),这就是打开无法正常工作的原因. /p>

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

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.

解决方案

"~" 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

这篇关于FileNotFoundError但文件存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆