Reply to the Luigi Russo's message, wrote on 04/10/2022 at 08:10:
Il 03/10/2022 23:56, Gabriele Battaglia ha scritto:
Ciao.
Chiedo venia per l'incredibile bruttezza di questa gestione errore.
Qui il fatto è che, dando ad input il nome di un file che esiste,
viene comunque richiamato il blocco except.
Il semplice codice è questo:
fn = input("The document has to be encoded in UTF-8\nfilename.ext to
prepare? > ")
try:
f=open(fn, "rt",encoding="utf-8")
rig = f.readlines()
f.close()
print(f"File: {fn} found, with {len(rig)} lines of text.")
except:
print(f"Sorry, file: {fn} not found.\nRelaunch the App and try
with another filename.")
sys.exit()
Gigi:
Ciao Gabriel,
il blocco except così come è scritto gestisce qualunque eccezione, per
cui non è detto che il problema sia il file che non è stato trovato.
Dovresti fare questo:
try:
f=open(fn, "rt",encoding="utf-8")
rig = f.readlines()
f.close()
print(f"File: {fn} found, with {len(rig)} lines of text.")
except FileNotFoundError:
print(f"Sorry, file: {fn} not found.\nRelaunch the App and try with
another filename.")
sys.exit()
Se il file non esiste ok, ma se però il problema è un altro ti viene
mostrato il traceback e quindi puoi capire perché c'è questo ulteriore
problema.
Hai ragione Gigi! Ciao intanto, grazie mille. Infatti seguendo il tuo
suggerimento e quello dell'altro ragazzo che mi ha scritto, ho risolto.
A presto.
Gabry.
_______________________________________________
Python mailing list
Python@lists.python.it
https://lists.python.it/mailman/listinfo/python