Python Forum
cant save data to text file.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
cant save data to text file.
#21
(Oct-29-2017, 01:55 AM)Larz60+ Wrote: Ok, this code works:
from tkinter import *
import tkinter as tk
from tkinter import filedialog
import sys, os
import io


class StatusBar(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        # self.file = io.open('märkning.txt', 'wt', encoding='utf8')
        self.file_open = False
        self.file = None

    def funktion(self):
        print('getting funked up')
        value1 = (a1.get())
        value2 = (a2.get())
        value3 = (a3.get())
        # value4 = (a4.get())

        for parts in range(value3):
            print('{}-{}-{}-{}\n'.format(value1, value2, parts + 1, parts + 1))
            # self.file.writelines('{}-{}-{}-{}\n'.format(value1, value2, parts+1, parts+1))
            a4.set('{}-{}-{}-{}\n'.format(value1, value2, parts + 1, parts + 1))

    # Vad ska programet göra när den stängs av.
    def On_exit(self):
        try:
            if self.file_open:
                print('closing')
                # stänger ner data filer och sparar data.
                self.file.close()
            # stäng av prgramet
            self.master.destroy()
        except:
            self.master.destroy()

    # Koden är en del av entry's endast nummer restriktion
    def validate(self, action, index, value_if_allowed,
                 prior_value, text, validation_type, trigger_type, widget_name):
        if text in '0123456789.-+':
            try:
                float(value_if_allowed)
                return True
            except ValueError:
                return False
        else:
            return False

    def file_save(self):
        if not self.file_open:
            print('opening')
            # file = filedialog.asksaveasfilename(initialdir = "/",title = "Select file",filetypes = (("txt files","*.txt"),("all files","*.*")))
            self.file = filedialog.asksaveasfile(mode='a+', filetypes=(("txt files", "*.txt"), ("all files", "*.*")))
            self.file_open = True
        value4 = (a4.get())
        print('writing')
        self.file.write(a4.get())
        # if file:
        #     file.writelines(value4)
        #     file.close()


if __name__ == "__main__":
    root = tk.Tk()
    status = StatusBar(root)
    root.protocol("WM_DELETE_WINDOW", status.On_exit)
    Frame = tk.Frame(root, borderwidth=10)
    Frame.grid(column=0, row=0, sticky=(N, W, E, S))
    # Koden är en del av entry's endast nummer restriktion
    vcmd = (Frame.register(status.validate),
            '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')

    a1 = StringVar()
    a2 = StringVar()
    a3 = IntVar()
    a4 = StringVar()

    text1 = Label(Frame, text="Kabelnamn:", font=("Helvetica", 12, "bold")).grid(column=0, row=0, sticky=(W),
                                                                                 columnspan=2)
    Kabelnamn_entry = tk.Entry(Frame, font=('Helvetica', 12, 'bold'), textvariable=a1)
    Kabelnamn_entry.grid(column=0, row=1, sticky=(W, E), columnspan=2)
    Kabelnamn_entry.delete(0, END)

    text2 = Label(Frame, text="Kabelnummer:", font=("Helvetica", 12, "bold")).grid(column=0, row=2, sticky=(W),
                                                                                   columnspan=2)
    Kabelnummer_entry = tk.Entry(Frame, font=('Helvetica', 12, 'bold'), textvariable=a2)
    Kabelnummer_entry.grid(column=0, row=3, sticky=(W, E), columnspan=2)
    Kabelnummer_entry.delete(0, END)

    text3 = Label(Frame, text="Parter:", font=("Helvetica", 12, "bold")).grid(column=0, row=4, sticky=(W), columnspan=2)
    part_entry = tk.Entry(Frame, font=('Helvetica', 12, 'bold'), textvariable=a3, validate='key', validatecommand=vcmd)
    part_entry.grid(column=0, row=5, sticky=(W, E), columnspan=2)
    part_entry.delete(0, END)

    button1 = tk.Button(Frame, text="Make", command=status.funktion, width=16)
    button1.grid(column=0, row=6, sticky=(W, E), columnspan=4)

    button2 = tk.Button(Frame, text="Spara", command=status.file_save, width=16)
    button2.grid(column=0, row=7, sticky=(W, E), columnspan=4)

    root.update()
    root.resizable(width=False, height=False)
    root.mainloop()
The file is opened as a+ (so it picks up from the last session),
if you want  new file for each session, change the mode to 'w'.
You don't need the t, as text is the default mode.
I added a file_open switch, and only open the file once, and then check is the flag is set at the and, and if so, close.

I changed the save routine a bit, removed the close, and write from a4 directly.

Hope this is what you wanted.

not really it still saves the last line which was my problem all along since the beginning. What i have been trying to do is to make it save all the lines it generet.

for example i generete this list 
Quote:save-this-1-1

save-this-2-2

save-this-3-3

save-this-4-4

save-this-5-5

save-this-6-6

save-this-7-7

save-this-8-8

save-this-9-9

save-this-10-10
 
then i want to save all this lines and no just one line.
Reply
#22
The results that you are showing were not created with the code that you supply.
There is no save-this anywhere in that code.

a4 (as stated previously) only has one line in it when the save routine is called.
You can't write more data that what is supplied.

The changes that I added will write one line every time the save button is pushed in your GUI.

If pushed 5 times, you'll get 5 lines of output, all the same if the data's not changed.
Reply
#23
(Oct-29-2017, 03:20 AM)Larz60+ Wrote: The results that you are showing were not created with the code that you supply.
There is no save-this anywhere in that code.

a4 (as stated previously) only has one line in it when the save routine is called.
You can't write more data that what is supplied.

The changes that I added will write one line every time the save button is pushed in your GUI.

If pushed 5 times, you'll get 5 lines of output, all the same if the data's not changed.

Ok but is it possible to save all the lines with a save dialog and if so how do i do it?
Reply
#24
Yes, supply more lines to the write routine!
Reply
#25
(Oct-29-2017, 03:27 AM)Larz60+ Wrote: Yes, supply more lines to the write routine!
Quote:a4 (as stated previously) only has one line in it when the save routine is called.
You can't write more data that what is supplied.

I asked if the a4 was the fault of the code earlier for what i wanted to do you told me no it ok.  anyways if "range" generate a bunch of lines how do i save them to the file via an save dialog? shouldent i buffer them somehow some where first till the file gets created?
Reply
#26
Suggest you reread the posts. I have repeatedly stated that a4 only had one line in it!
Reply
#27
(Oct-29-2017, 03:48 AM)Larz60+ Wrote: Suggest you reread the posts. I have repeatedly stated that a4 only had one line in it!

Yes and i have repeatedly stated that i wanted to save all the lines genereated in to a text file with a save dialog.
Anyway whats the salutation? im guessing i still need to buffer all the lines range generate in to somewhere before being able to save it to a file with a save dialog?
Reply
#28
If you will try the following, I think you will have what you want.
Using the code with my changes in it.
  • fill out the form as follows
  • set kabelnamn to save-this
  • set Kabelnummer 1
  • set Parter 1
  • press Make
  • press Spara
  • fill out the form as follows
  • set kabelnamn to save-this
  • set Kabelnummer 2
  • set Parter 2
  • press Make
  • press Spara
  • Click X (upper right of form)
  • Look at your file

You should have two lines because you entered two items

You don't need to buffer for this
Reply
#29
(Oct-29-2017, 05:02 AM)Larz60+ Wrote: If you will try the following, I think you will have what you want.
Using the code with my changes in it.
  • fill out the form as follows
  • set kabelnamn to save-this
  • set Kabelnummer 1
  • set Parter 1
  • press Make
  • press Spara
  • fill out the form as follows
  • set kabelnamn to save-this
  • set Kabelnummer 2
  • set Parter 2
  • press Make
  • press Spara
  • Click X (upper right of form)
  • Look at your file

You should have two lines because you entered two items

You don't need to buffer for this    

The problem with this is it would take ages to make all the kabel markings we got some times kabels with like 100 parts in them it would require ages to do them all if im going to do it like in your description. But with some tinkering i think i solved it in a diffrent way i dont know if its a stupid solution or not. But here how i did it. I added a big text entry where the generated lines say 100 lines of kabel markings get stored and when i press save all those lines gets saved to a text file. I have no idea how to do it any other way.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Open/save file on Android frohr 0 316 Jan-24-2024, 06:28 PM
Last Post: frohr
  how to save to multiple locations during save cubangt 1 543 Oct-23-2023, 10:16 PM
Last Post: deanhystad
  save values permanently in python (perhaps not in a text file)? flash77 8 1,206 Jul-07-2023, 05:44 PM
Last Post: flash77
  Save and Close Excel File avd88 0 3,021 Feb-20-2023, 07:19 PM
Last Post: avd88
Thumbs Up Need to compare the Excel file name with a directory text file. veeran1991 1 1,114 Dec-15-2022, 04:32 PM
Last Post: Larz60+
  Save multiple Parts of Bytearray to File ? lastyle 1 941 Dec-10-2022, 08:09 AM
Last Post: Gribouillis
  Modify values in XML file by data from text file (without parsing) Paqqno 2 1,657 Apr-13-2022, 06:02 AM
Last Post: Paqqno
  Converted Pipe Delimited text file to CSV file atomxkai 4 6,956 Feb-11-2022, 12:38 AM
Last Post: atomxkai
  Save data frame to .csv df.to.csv() mcva 1 1,526 Feb-03-2022, 07:05 PM
Last Post: mcva
Sad Want to Save Print output in csv file Rasedul 5 10,911 Jan-11-2022, 07:04 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020