python3 中的文件目录错误

File Directory error in python3

对于我的程序,我有 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'

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

-谢谢

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