问题描述
代码:
我试图打开这个文件,但 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")
所做的是搜索名为 rubrica
的 ANOTHER 文件夹,该文件夹是您的 {{1} 的SIBLING } 文件,它根本不存在。
account.py