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.
#11
can this line be the fault ?
That should create a standard properly terminated string, not a problem

what does a4 look like before the write?
do a
print(a4)
just before the write.
Reply
#12
(Oct-27-2017, 08:37 PM)Larz60+ Wrote: can this line be the fault ?
That should create a standard properly terminated string, not a problem

what does a4 look like before the write?
do a
print(a4)
just before the write.

I have been using print(a4) to check up what the string contains and its the same only the last line gets printed.

which is when i generate this
Quote:kp1234-w3-1-1

kp1234-w3-2-2

kp1234-w3-3-3

kp1234-w3-4-4

kp1234-w3-5-5

kp1234-w3-6-6

kp1234-w3-7-7

kp1234-w3-8-8

kp1234-w3-9-9

kp1234-w3-10-10
Quote:only this kp1234-w3-10-10 line gets printed for some reason.
Reply
#13
do one more thing:
change:
        value4 = (a4.get())
        if file:
            file.writelines(value4)
            file.close()
to:
        value4 = (a4.get())
        print('value4 data type{}, contents{}'.format(type(value4), value4))
        if file:
            file.writelines(value4)
            file.close()
and post what comes out
Reply
#14
(Oct-28-2017, 04:24 AM)Larz60+ Wrote: do one more thing:
change:
        value4 = (a4.get())
        if file:
            file.writelines(value4)
            file.close()
to:
        value4 = (a4.get())
        print('value4 data type{}, contents{}'.format(type(value4), value4))
        if file:
            file.writelines(value4)
            file.close()
and post what comes out

I get 
Quote:value4 data type<class 'str'>, contentskp1234-w3-10-10

i think the string only contains the last line of the list generated.
Reply
#15
Well, you can't write more than what's there!
The content of value4 is: skp1234-w3-10-10
so that's all that will be written.
The code is doing exactly what it is being told to do.
Reply
#16
(Oct-28-2017, 10:35 AM)Larz60+ Wrote: Well, you can't write more than what's there!
The content of value4 is: skp1234-w3-10-10
so that's all that will be written.
The code is doing exactly what it is being told to do.

Ok how can i then make it save all the lines the generator generate to the text file with a save dialog?
Reply
#17
I think the original question was unclear.
So I guess you are asking how to you save completely new entries to the same file.
Is this correct?
Reply
#18
(Oct-28-2017, 04:56 PM)Larz60+ Wrote: I think the original question was unclear.
So I guess you are asking how to you save completely new entries to the same file.
Is this correct?

Yea if i generate 10 lines how can i save all this 10 lines to a text file via a save dialog?
Reply
#19
Ok, give me a bit of time. I'll be back soon!
Reply
#20
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Reading an ASCII text file and parsing data... oradba4u 2 220 Jun-08-2024, 12:41 AM
Last Post: oradba4u
  Open/save file on Android frohr 0 440 Jan-24-2024, 06:28 PM
Last Post: frohr
  how to save to multiple locations during save cubangt 1 652 Oct-23-2023, 10:16 PM
Last Post: deanhystad
  save values permanently in python (perhaps not in a text file)? flash77 8 1,430 Jul-07-2023, 05:44 PM
Last Post: flash77
  Save and Close Excel File avd88 0 3,436 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,243 Dec-15-2022, 04:32 PM
Last Post: Larz60+
  Save multiple Parts of Bytearray to File ? lastyle 1 1,030 Dec-10-2022, 08:09 AM
Last Post: Gribouillis
  Modify values in XML file by data from text file (without parsing) Paqqno 2 1,861 Apr-13-2022, 06:02 AM
Last Post: Paqqno
  Converted Pipe Delimited text file to CSV file atomxkai 4 7,340 Feb-11-2022, 12:38 AM
Last Post: atomxkai
  Save data frame to .csv df.to.csv() mcva 1 1,664 Feb-03-2022, 07:05 PM
Last Post: mcva

Forum Jump:

User Panel Messages

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