【问题标题】:File Directory error in python3python3中的文件目录错误
【发布时间】:2016-09-03 01:48:13
【问题描述】:

对于我的程序,我有 3 个程序 它们都将在下面列出

C:\Python\data\fold1\subfile.py

import json
import sys

part = sys.path[0].split('\\')                  '''This part adds
del (part[part.index('Python') + 1:len(part)])     a system path
sys.path.insert(1, '\\'.join(part))                C:\Python'''

from data.fold2.other import accounts_list

class AddUser():
    def __init__(self, username, password, Type=1):
        self.username = username
        self.password = password
        self.Type = Type
        accounts_list[self.username] = [self.password, self.Type]
        with open('data\\fold2\\other.py', 'w') as file:
            file.write('accounts_list = ' + json.dumps(accounts_list))

C:\Python\data\fold2\start.py

import sys
from other import accounts_list

part = sys.path[0].split('\\')                 '''This part adds
del (part[part.index('Python') + 1:len(part)])    a system path
sys.path.insert(1, '\\'.join(part))               C:\Python'''

from data.fold1 import subfile

subfile.AddUser('username', 'password')

C:\Python\data\fold2\other.py

accounts_list = {}

当我运行我的主程序时,启动,我得到了错误:

  File "C:\Python\data\fold1\subfile.py", line 16, in __init__
    with open('data\\fold2\\other.py', 'w') as file:
FileNotFoundError: [Errno 2] No such file or directory:                 'data\\fold2\\other.py'

我不知道如何解决这个错误,因为我还是个初学者。 如果有人知道该怎么做,请提供答案。

-谢谢

【问题讨论】:

    标签: python-3.x import path sys


    【解决方案1】:

    在打开文件方面,我建议您查看:Open file in a relative location in Python 否则,您的问题只是如上所述,您正在尝试访问不存在的文件。要在子文件夹之间切换,只需使用 ../fold2/other.py

    【讨论】:

    • 我知道该目录通常不在 sys.path 中,所以我在代码中添加了它?如果 ... 是 C:\Python 等,我真的无法补充,因为该程序位于多台不同的计算机上,因此它将保存在不同的位置。
    • 我也尝试从 ..data.fold2 等添加。并得到错误: SystemError: Parent module '' not loaded, cannot perform relative import
    • @Nic 你没有改变你的工作目录。执行类似于os.chdir('/path/...') 的操作。虽然在我看来,使用相对依赖更有意义。
    • 什么是相对依赖?我还是 python 的初学者。
    • 在一个包中,子目录不包括在内;您需要“链接”目录。 (添加__init__.py 文件)就相对依赖而言,只需查看我发布的链接即可。
    猜你喜欢
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2018-12-20
    • 1970-01-01
    • 2021-05-08
    相关资源
    最近更新 更多