为什么程序找不到文件? python 谢谢

问题描述

代码:

enter image description here

我试图打开这个文件,但 Python 没有找到它。

    import os,shutil,re,random
        #categoria a caso
        cat= random.choice(categorie)
        
        string = str(input("Inseriisci nome utente e password\n"))  
        string=string+" "+cat
       
        lista = open((os.path.join("rubrica","lista.txt")),"a")
        lista.write(f"\n{string}")
        lista.close()

错误是:

Traceback (most recent call last):
  File "c:\Python\progetti\base_allenamento\rubrica\accounts.py",line 30,in <module>
    lista = open((os.path.join("rubrica","a")
FileNotFoundError: [Errno 2] No such file or directory: 'rubrica\\lista.txt'

我不知道如何解决这个问题。

解决方法

如果您的 accounts.py 文件与您尝试打开的文件在同一个文件夹中,则不需要使用 os.path,您只需执行以下操作:

lista = open('lista.txt','a')
,

你的文件结构看起来像这样

- rubrica (folder)
---- accounts.py (file)
---- lista.txt  (file)

您需要搜索 lista.txt relative 到您的脚本 account.py 这是一个兄弟。所以正确的应该是这两个

lista = open("./lista.txt")  # this works
# or list = open("lista.txt")

您通过调用 os.path.join("rubrica","lista.txt") 所做的是搜索名为 rubricaANOTHER 文件夹,该文件夹是您的 {{1} 的SIBLING } 文件,它根本不存在。

account.py

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...