Python Forum

Full Version: cancelling open dialog gives empty string
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I am trying to open a file using the file dialog but what if the user decides to press cancel? a new line is added to my text widget. I don't want that extra line added there, how to achieve that?

text_file = filedialog.askopenfilename(initialdir="C:/Documents", title="Open File",
        filetypes=(("Text Files", "*.txt"),("HTML Files", "*.html"),
                   ("Python Files", "*.py"), ("All Files","*.*")))

    if (len(text_file) !=0):
        my_text.delete("1.0", END)
        open_status_name = text_file
        name, file_extension = os.path.splitext(text_file)
        name = name.split('/')[-1].split('.')[0]
        root.title(name+file_extension)
        status_bar.config(text = "File Opened Successfully!        ")
        text_file = open(text_file,"r")
        stuff = text_file.read()
        my_text.insert(END, stuff)
        text_file.close()
   else:
what i need to do in the else statement to delete that extra line because the user cancelled the operation?

Thanks
Prefix your question with what GUI you are using. Better yet, make your example code complete so others can run it.

I don't see where you are adding anything to a text widget if text_file is empty.
Assuming this code is in a function (it probably should be), then;

if text_file = "":
    return
after the filedialog line.


(Jul-01-2021, 01:04 PM)rwahdan Wrote: [ -> ]Hi,

I am trying to open a file using the file dialog but what if the user decides to press cancel? a new line is added to my text widget. I don't want that extra line added there, how to achieve that?

text_file = filedialog.askopenfilename(initialdir="C:/Documents", title="Open File",
        filetypes=(("Text Files", "*.txt"),("HTML Files", "*.html"),
                   ("Python Files", "*.py"), ("All Files","*.*")))

    if (len(text_file) !=0):
        my_text.delete("1.0", END)
        open_status_name = text_file
        name, file_extension = os.path.splitext(text_file)
        name = name.split('/')[-1].split('.')[0]
        root.title(name+file_extension)
        status_bar.config(text = "File Opened Successfully!        ")
        text_file = open(text_file,"r")
        stuff = text_file.read()
        my_text.insert(END, stuff)
        text_file.close()
   else:
what i need to do in the else statement to delete that extra line because the user cancelled the operation?

Thanks