簡體   English   中英

為什么程序找不到文件? python 謝謝

[英]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.pylista.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM