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.
#1
hi
Im trying to save all the generated numbers from my generator  to a text file with file save dialog but it only saves the last line and the text file does not have *.txt for some reason. Could any one help me out?

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')


    def funktion(self):
        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:
            #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):
        
        #file = filedialog.asksaveasfilename(initialdir = "/",title = "Select file",filetypes = (("txt files","*.txt"),("all files","*.*")))
        file = filedialog.asksaveasfile(mode='wt', filetypes = (("txt files","*.txt"),("all files","*.*")))
        value4 = (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()
Reply
#2
shouldn't the mode be plain 'w', rather than 'wt'? (line 48)
Reply
#3
(Oct-26-2017, 09:30 PM)Larz60+ Wrote: shouldn't the mode be plain 'w', rather than 'wt'? (line 48)

Well thats not the problem w and wt is alost the same thing here. My problem is if i generete 10 lines of data and save it only the 10th or last line is saved to the file and the file does not get the *.txt 


The t indicates text mode, meaning that \n characters will be translated to the host OS line endings when writing to a file, and back again when reading. The flag is basically just noise, since text mode is the default.
Reply
#4
'wt' was foreign to me, I had at some point assumed that the file modes
were the same as 'C' file modes, but then saw the python 'wt' mode after my post.
Learned something new!

That being the case, change writelines to write, writelines expects a list of strings,
while write expects a single string.
Reply
#5
(Oct-27-2017, 08:26 AM)Larz60+ Wrote: 'wt' was foreign to me, I had at some point assumed that the file modes
were the same as 'C' file modes, but then saw the python 'wt' mode after my post.
Learned something new!

That being the case, change writelines to write, writelines expects a list of strings,
while write expects a single string.

It did not help it still writes the last line to the text file.
Reply
#6
'wt' ?
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#7
wavic it's two vaniyas!, got me too, but it's valid!
Reply
#8
(Oct-27-2017, 04:33 PM)Larz60+ Wrote: wavic it's two vaniyas!, got me too, but it's valid!

i am  still only saving  the last line that the generator generate to the text file while i want to save all lines. i cant figure out why.

for examle if i generate 
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 saved for some reason.
Reply
#9
what does a4 look like?

could this have something to do with it?
    #value4 = (a4.get())
That's commented out
Reply
#10
(Oct-27-2017, 04:49 PM)Larz60+ Wrote: what does a4 look like?

could this have something to do with it?
    #value4 = (a4.get())
That's commented out

That line was commented out for another experimental reason. But its the a4 string which i want to save to text file. The code  that generate the data is

    def funktion(self):
        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))
can this line be the fault ?

a4.set('{}-{}-{}-{}\n'.format(value1, value2, parts+1, parts+1))
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Open/save file on Android frohr 0 278 Jan-24-2024, 06:28 PM
Last Post: frohr
  how to save to multiple locations during save cubangt 1 509 Oct-23-2023, 10:16 PM
Last Post: deanhystad
  save values permanently in python (perhaps not in a text file)? flash77 8 1,118 Jul-07-2023, 05:44 PM
Last Post: flash77
  Save and Close Excel File avd88 0 2,839 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,061 Dec-15-2022, 04:32 PM
Last Post: Larz60+
  Save multiple Parts of Bytearray to File ? lastyle 1 907 Dec-10-2022, 08:09 AM
Last Post: Gribouillis
  Modify values in XML file by data from text file (without parsing) Paqqno 2 1,575 Apr-13-2022, 06:02 AM
Last Post: Paqqno
  Converted Pipe Delimited text file to CSV file atomxkai 4 6,840 Feb-11-2022, 12:38 AM
Last Post: atomxkai
  Save data frame to .csv df.to.csv() mcva 1 1,495 Feb-03-2022, 07:05 PM
Last Post: mcva
Sad Want to Save Print output in csv file Rasedul 5 10,681 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