Save As, each filetype has different callback function
I use python tkinter, and Import tkinter.filedialog to save as files. The program has functions to save each file type.
Using filedialog.asksaveasfilename
Returns file path only.
The Problem: how to get the file type, to call the right function?
Below is a sample Code of what I did.
python
filename= filedialog.asksaveasfilename(title="Select file", filetypes=(("PNG", "*.png"), ("EPS", "*.eps"), ("TXT", "*.txt"), ("XML", "*.xml")))
if filetype is TYPE_1:
function_1()
elif filetype is TYPE_2:
function_2()
Asked by: Cherry937 | Posted: 27-01-2022
Answer 1
You can add the option defaultextension='.'
to filedialog.asksaveasfilename()
and then what ever extension the user selects within the Save Dialog window will be used as the "default extension" and that extension will be appended to the path of the saved file. You can then retrieve the extension with os.path.splitext()
as shown below.
I also used a named tuple for the filetypes=
option because I think it looks nicer but it is not necessary by any means.
import os
import tkinter as tk
from collections import namedtuple
from tkinter import filedialog
class MainApplication:
def __init__(self, parent):
self.b1 = tk.Button(parent, text='Save', command=self.save_dialog)
self.b1.pack()
def png(self):
print('DO SOMETHING WHEN FILE EXT IS .PNG')
def eps(self):
print('DO SOMETHING WHEN FILE EXT IS .eps')
def txt(self):
print('DO SOMETHING WHEN FILE EXT IS .txt')
def xml(self):
print('DO SOMETHING WHEN FILE EXT IS .xml')
def save_dialog(self):
Types = namedtuple('Types', 'name ext')
png = Types('PNG', '.png')
eps = Types('EPS', '.eps')
txt = Types('TXT', '.txt')
xml = Types('XML', '.xml')
path = filedialog.asksaveasfilename(title='Select file',
defaultextension='.',
filetypes=(png, eps, txt, xml)
)
filename, ext = os.path.splitext(path)
if ext == png.ext:
self.png()
elif ext == eps.ext:
self.eps()
elif ext == txt.ext:
self.txt()
elif ext == xml.ext:
self.xml()
if __name__ == '__main__':
root = tk.Tk()
MainApplication(root)
root.mainloop()
Answered by: Vanessa728 | Posted: 28-02-2022
Similar questions
python - Filetype information
I'm in the process of writing a python script, and I want to find out information about a file, such as for example a mime-type (or any useful depiction of what a file contains).
I've heard about python-magic, but I'm really looking for the solution that will allow me to find this information, without requiring the installation of additional packages.
Am I stuck to maintaining a list of file extens...
How to know the filetype through python
In the very beginning,I tried to do like this(hoped to get some useful information in the head):
>>content=open("fileurl","rb").read()
I found that PNG (png)'s Header is lik this: 89504E47 (I don't know wheather it's true or not)
But when I did in this way,the result is:
>>> content[:20]
'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x01\x90'
the \xis wha...
VIM python filetype specific indent fails after 50 lines of one list
I'm currently working on reformatting a python project to follow the 4 spaces indent style. The project is being done in VIM with the following plugins: fugitive, snipmate, surround, git, supertab, minibufexpl, command-t. pyflakes-pathogen, ack, gundo, pydoc, pep8, py.test, makegreen, tasklist, nerdtree, ropevim .
My .vimrc is currently:
set tabstop=4
set shiftwidth=4
set expandtab
let mapleader="...
python - Django- Check the filetype of an uploaded file and then alter the template
I want to write a function that checks the extension of the uploaded file and depending on that assigns a variable a value.
I hope it makes sense. I basically want to check the filetype of an uploaded file and then alter the template accordingly.
The code that I am thinking of implementing is something like this but I am kind of confused
models.py
class ScribbleMedia(models.Model):
...
How to serve filetype object in python
I'm using the URLLib2 method to download a file from another server via a rest api (the url can't be exposed to the user--that's why it needs to be done on the backend).
It gives me the following response:
(<addinfourl at 4365818480 whose fp = <google.appengine.dist27.socket._fileobject object at 0x1043883d0>>
I'm now trying to find a way to serve this file to the end...
Python: A way to detect a filetype attached to a string?
In IronPython 2.6*, I'm trying to build a function that "corrects" a string; I have two arguments, FILE and EXTN. The idea is for them to be concatenated as necessary later in the program, but you know some people don't read instructions and you're bound to have someone enter "FILE.*" as their FILE, which would mess everything up.
I'm looking for a way to take
file - Python frozen app filetype
I've got a python GUI application (wx) that is able to open zip files with an alternate extension (.giz).
def GetGIZData(self, filepath):
#{extract the zip to a temp dir and read the files}
pass
My question is this: if I've got a file at C:\InputFile.giz, how do I get a handle on "C:\InputFile.giz" from a frozen python app in Windows when I double click on InputFile.giz? (Essentia...
Python: How to find google drive filetype?
I'm currently using the session.get() code found at this stackoverflow. When I save the drive files they don't have a filetype suffix, so I have to add one manually to based on file type to open it. Is there a way I can parse the chunk and get filetype variable or maybe even search by hexcode? Better method?
import requests
def download_file_from_google_drive(id, destination):
URL = "https://docs.google...
python - batch file to open custom filetype
I have a custom filetype (.photon) that is read by a python script which I generally run like this in a terminal:
py C:\Users\greym\Desktop\photon\photon.py C:\Users\greym\Desktop\photon\test.photon
the last argument is the file that is read by the python script how I make it so I can click on that file and it will run it through the python script
Trying to open a certain filetype using my python exe
I made a simple python file encryptor. I want to open all encrypted (or .aes) files using my program. I have already made it into a working executable using pyinstaller but when I tried to open a .aes file with my program (through the context menu in the file explorer), it unsurprisingly started the program but did not take the .aes file as input. I want to open any .aes file using my program and for the python script to s...
Still can't find your answer? Check out these communities...
PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python