Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello β I'm @olemoritz on Twitter.
Extracting the Date from the UI date and time spinner
-
@abushama, I am not really sure what your final result is suppose to look like. But if you look below there is a function that will take a dict and write it out to the csv file. So that function is only concerned with your csv file, not how to get the data. If you call the function over and over it will be ok, because we only write the headers out once.
import csv import os def write_to_csv(filename, data_dict): fexists = os.path.exists(filename) # We set a var to see if the file exists fieldnames = list(my_data_dict.keys()) # get a list of the keys to use as the header with open(filename, 'a') as csvfile: #fieldnames = ['Day', 'Month','Year'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) # only write the header one time to the file if not fexists: writer.writeheader() writer.writerow(data_dict) #svfile1.close() # you dont need this. Look up Context Managers if __name__ == '__main__': filename = 'my_csv.csv' # you would collect your data and put it in a dict. my_data_dict = dict( Day = 1, Month = 12, Year = 2017, Amm = 2.5 ) write_to_csv(filename , my_data_dict) # just print the file to the console, make sure its what we wanted with open(filename) as f: for line in f: print(line, end='')
-
@Phuket2
am trying to post a screenshot of my UI but i dont know how??
may u send my ur email plz? -
Posting images to this forum works like this: https://guides.github.com/features/mastering-markdown/#examples
-
-
Perhaps the missing magic in this thread is seek() which lets you open a file in
'a'
mode and then seek to the beginning of that file (append_file.seek(0, 0)) so that you can read() its contents and then seek to the end of the file (append_file.seek(0, 2)) and then write() new content to the end of the file. -
@ccc, I am a little baffled. I was going to suggest he could call the function twice with different files names then have another small function to combine the files or create a 3rd file. Whatever is needed.
Maybe should have done this without using csv to help for clarity the fact its only a comma separated file with some headings if required. The csv writer in this case would only help with imbedded quotes in strings etc...In this simple case.
The dict writer is nice though.
We will see what @abushama comes back with. -
It seems to me, he wants a function which gathers the entire UI state, not just the sender, and write that to csv.
i.e there should be a utility function which gets the date, as well as everything else he wants in the file, and writes the csv. Then both callbacks call the exact same function.
-
-
this is my UI simple project
i hope this give u a quite view -
@JonB
exatly..i input
the first three cells
GontarHighPrice
GontarLowPrice
and the doller rate
then i tunning the calnder celnder to the certin date and press calculate botton
this action will calculte other cells in the UI and in the same time will save this all this data + the date in one csvwhat i got so far in the code above all the data and the date
but not in one order -
@abushama , as far as I can see the below should do want you want, if not pretty close to it. I am not saying its the prettiest way to do it. But its very procedural. Hopefully its easy to follow. There are always many solutions to a given problem. I have tried to do it as I imagine you are doing it. I mean by loading the form. I assume in the designer for the button you are setting the action to call.
For the below to work you need to set your calc button's action to calc_button_action and you have to set the my_screen_fn to the name of your view you made in the Designer.import ui from os.path import exists import csv _csv_filename = 'myoutput.csv' def calc_button_action(sender): ''' Here your calc button will call 3 functions. 1. do_calculations, so you calculate and put the values in your fields 2. collect_data, will collect all the data from your view and return it as a dict 3. write_to_csv, you pass your dict you collected the data into and it will be written to the csv file. The file name is at the top of the file. You could ask for the name of the file for example. ''' # v is set to your view, so you can access the other objects on you view now and # pass your view to other functions! v = sender.superview do_calculations(v) data_dict = collect_data(v) write_to_csv(_csv_filename, data_dict) def do_calculations(v): ''' in here, just do your calculations and update your fields with the calculated data ''' # so to access the date in the ui.DatePicker, lets say its name is cal the_date = v['cal'].date # you can access all your objects as above. v['txt9'].text = str(10 * 2) # whatever you calculate def collect_data(v): ''' in here you are only intrested in collecting your data from the view again, you have the view so you can access your fields. I have used a dict here to collect the information. I think if you are using py 3.6, your dict will keep its order as you add your items ''' # I have only filled in a few fields here. But you would add everything from your view # you wanted written out to the csv. Add the items in the order you want them written # to the csv file. d = dict( Year = v['cal'].date.year, Month = v['cal'].date.month, Day = v['cal'].date.day, HighPrice = v['txt9'].text, ) return d def write_to_csv(filename, data_dict): ''' This function is only concerned with writing your dict to the csv file. ''' fexists=exists(filename) # We set a var to see if the file exists fieldnames = list(data_dict.keys()) # get a list of the keys to use as the header with open(filename, 'a') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=fieldnames) # only write the header one time to the file if not fexists: writer.writeheader() writer.writerow(data_dict) if __name__ == '__main__': my_screen_fn = 'someview.pyui' v = ui.load_view(my_screen_fn) v.present(style='sheet', animated=False)
-
@Phuket2
thank you very much
frist thing u taught how to
combin funtions in my UI which i do not know before.
2)ur code is so clear to get the idea simplyas u side am not using 3.6 python so the output of dic are not orginize as i put in my code
so any idea..? -
@abushama , ok here is a version that is using lists. I thought it should be a simple change to use OrderDict, but I had a problem to get it to work. So i used a list instead :(
import ui from os.path import exists import csv _csv_filename = 'myoutputV2.csv' def calc_button_action(sender): ''' Here your calc button will call 3 functions. 1. do_calculations, so you calculate and put the values in your fields 2. collect_data, will collect all the data from your view and return it as a list 3. write_to_csv, you pass your list you collected the data into and it will be written to the csv file. The file name is at the top of the file. You could ask for the name of the file for example. ''' # v is set to your view, so you can access the other objects on you view now and # pass your view to other functions! v = sender.superview do_calculations(v) data_list = collect_data(v) write_to_csv(_csv_filename, data_list , ['Year', 'Month', 'Day', 'HighPrice']) def do_calculations(v): ''' in here, just do your calculations and update your fields with the calculated data ''' # so to access the date in the ui.DatePicker, lets say its name is cal the_date = v['cal'].date # you can access all your objects as above. v['txt9'].text = str(10 * 2) # whatever you calculate def collect_data(v): ''' in here you are only intrested in collecting your data from the view again, you have the view so you can access your fields. Using a list now! not a dict ''' lst = [] # I have only filled in a few fields here. But you would add everything from your view # you wanted written out to the csv. Add the items in the order you want them written # to the csv file. lst.append(v['cal'].date.year) lst.append(v['cal'].date.month) lst.append(v['cal'].date.day) lst.append(v['txt9'].text) return lst def write_to_csv(filename, data_list, field_name_list=None): ''' This function is only concerned with writing your list to the csv file. ''' fexists=exists(filename) # We set a var to see if the file exists with open(filename, 'a') as csvfile: csvwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) if not fexists and field_name_list != None: csvwriter.writerow(field_name_list) csvwriter.writerow(data_list) if __name__ == '__main__': my_screen_fn = 'someview.pyui' v = ui.load_view(my_screen_fn) v.present(style='sheet', animated=False)
-
@Phuket2
what about the header of the list??
#fieldnames = list(data_dict.keys()) # get a list of the keys to use as the header
as long we use list we skip an important figer whish the header of the cells
my Quation is can we cobine the two methods
(dict )for header and( list )for appending the value?
like dict is outer method and inside this dict sublist to store order data?? -
@Phuket2
i tried in both sides lists inside dict & and dicts inside one list
but i got invalid sentax π€π
any idea.. -
Can we get a GitHub repo here so that @abushama can post the original code and we can set in pull requests for targeted fixes? EDIT: added
fields
for readabilityfrom collections import namedtuple fields = ('year', 'month', 'day', 'text') note = namedtuple('note', fields) notes = [note(2017, 8, 11, 'yesterday'), note(2017, 8, 12, 'today'), note(2017, 8, 13, 'tomorrow')] fmt = '{:<10} {:<10} {:<10} {}' print(fmt.format(*fields)) for n in notes: print(fmt.format(*n)) """ year month day text 2017 8 11 yesterday 2017 8 12 today 2017 8 13 tomorrow """
-
@ccc, I made a repo here. I am not sure I did it in a smart way or not. I tried to give it a bit of structure in case have to help someone else, including myself :) in the future.
@ccc, I have looked for this, a permission to let anyone do what they want to the repo without having to invite them. So they can push, pull merge etc...It seems something like that would make sense for a repo like this.
Anyway, any thoughts to make the structure of the repo better would be appreciated. Even if i have to start again, that's ok. I did create the repo in github, web. But i was able to clone it, and push the pyui to it from Pythonista using StaSh. That's a big step for me. I am still not using ssh keys yet. I will get to that nextSide Note to @omz : Is there a thread id that you suppress in the forum's display? This would be handy for something like this when making a repo to work with someone on a forum problem....Just a though (btw, i just mean a single id for a thread, at the first message).
-
@abushama , I am not sure why you are getting an error. I copied the code straight from the post and pasted it into a new file and it worked. Well, some extra text is copied in that I had to delete, but that should be fairly obvious. But it works under 2.7 and 3.6.
But please when you get invalid syntax, or an error, copy it and paste it into your post. I know some of these things can be confusing when you are first getting started. But it should not take long before you start to get the hang of it. I would hold off on @ccc suggested code for the moment, even though it maybe better. Focus on get the list version going first. Once that's up and running correctly, can upgrade it and more Pythonetic.@abushama, the latest version of the code (list version as above) and the test pyui file is in a repo here. If you don't know about Github and repos, lets not get into that here on this post. I barely can use them.
But anyway, please look at the list version of the code closely. Make sure you haven't changed it accidentally or copied extra info from the post (look at the very top of you file).
If you still get the error, please copy the error and paste it in a post. If you do get it working, please let us know!Determined to get you going with this :)
-
I would hold off on @ccc suggested code
Always good advise. ;-) I edited my code above to make it easier to understand.
-
@Phuket2
it worksππ½
thank you