[英]Why the program can't find the file? python thanks
编码:
我正在尝试打开此文件,但 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", "lista.txt")), "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)
您需要搜索相对于您的脚本account.py
的lista.txt
,这是一个兄弟。 所以正确的将是这些
lista = open("./lista.txt") # this works
# or list = open("lista.txt")
相反,您通过调用os.path.join("rubrica", "lista.txt")
正在搜索rubrica
的文件夹,它是您的account.py
文件的SIBLING ,它根本不存在。
>>> os.path.join("rubrica", "lista.txt")
'rubrica/lista.txt'
# Here is how it is searching
# - rubrica (folder)
# ---- accounts.py (file)
# ---- lista.txt (file)
# ---- rubrica (folder) Here it is looking next to account.py for rubrica
# -------- lista.txt this does not exist
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.