简体   繁体   中英

python - recall browsed file

I'm writing a program where the user browses a pdf and select it. I would like to detect the file and send a pop up if the selected file is not a PDF. But the program, even if print the correct file type, does not send a pop up if the file is not a pdf. How can i do?

def OpenFile ():
    file1 = filedialog.askopenfile (initialdir ="/", mode ="r") #r sta per solo lettura
    print (file1)
    file_type = (mimetypes.MimeTypes().guess_type(file = 'file1'))
    x = file_type 

    if x == ('application/pdf') :
        messagebox.showinfo("Disclaimer","Upload done", icon ='info')
    else : 
        messagebox.showinfo("Disclaimer","choose a PDF file", icon ='warning')

this code doesn't work because it say:

 file_type = (mimetypes.MimeTypes().guess_type(file = 'file1'))
 TypeError: guess_type() got an unexpected keyword argument 'file

file is not a valid argument for the guess_type function. guess_type expects the filename to the file. If file1 is the name of your file then you want to do

file_type = mimetypes.MimeTypes().guess_type(file)

You can see the documentation for this function python docs

Relevant part:

mimetypes.guess_type(url, strict=True)

Guess the type of a file based on its filename or URL, given by url. The return value is a tuple (type, encoding) where type is None if the type can't be guessed (missing or unknown suffix) or a string of the form 'type/subtype', usable for a MIME content-type header.

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