1 year ago

#77007

test-img

alonsocontree

How can i detect if a file has already been opened in python

I hope you can help me, I'm new on python.

I am making a program in python with tkinter that requires opening a file and then converting it.

My problem is the conditional, because I need that when pressing the "Convert file" button it checks if the file has been selected first and if not, it shows a message that says "No file has been opened".

I think the problem is in the return opened_file_path. How can I make the string variable of the file path available to any function?

Here is my code, thank you.

from tkinter import filedialog
from tkinter import messagebox
from tkinter import *
import os
import re

window = Tk()
window.title("Blank-Space UXD deleter (beta)")
window.geometry('400x50')

def open_file():
    opened_file_path=filedialog.askopenfilename(initialdir = "/",
                title = "Select files",filetypes = (("TXT files","*.txt"),
                ("All files","*.*")))
    return opened_file_path

        
def convert_file():
    if opened_file_path == "":

        messagebox.showinfo(message="No file has been opened", title="Imposible to convert")
        
    else:
        
        file_name = opened_file_name
        file_name_mod = file_name.replace(".txt", "")
        file_name_mod = file_name_mod + "m.txt"
        mod_file = open(file_name_mod, 'w')
        raw_file = open(file_name, 'r')

        for x in raw_file:
            xf = re.sub(' +', ' ', x)
            xf = xf.lstrip()
            mod_file.write(xf)
            print(x)
            print(xf)


Button(text="Open file",command=open_file).place(x=10,y=10)
Button(text="Convert file",command=convert_file).place(x=150,y=10)
window.mainloop()

python

return

conditional-statements

verify

0 Answers

Your Answer

Accepted video resources