简体   繁体   English

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

[英]Why the program can't find the file? python thanks

The code:编码:

在此处输入图像描述

I'm trying to open this file but Python doesn't find it.我正在尝试打开此文件,但 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()

The error is:错误是:

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'

I have no idea about how to solve the problem.我不知道如何解决这个问题。

If your accounts.py file is in the same folder as the file you're trying to open, you don't need to use os.path, you can simply do:如果您的 accounts.py 文件与您尝试打开的文件位于同一文件夹中,则不需要使用 os.path,您可以简单地执行以下操作:

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

Your file structure looks something like this您的文件结构看起来像这样

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

You need to search for lista.txt relative to your script account.py which is a sibling .您需要搜索对于您的脚本account.pylista.txt ,这是一个兄弟 So the correct would be either of these所以正确的将是这些

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

What you are instead doing by calling os.path.join("rubrica", "lista.txt") is searching for ANOTHER folder named rubrica that is a SIBLING to your account.py file, which simply does not exist.相反,您通过调用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM