简体   繁体   中英

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.

    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:

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 . 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/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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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