[Tutor] Writing logfile data to a user opened file

Prasad, Ramit ramit.prasad at jpmorgan.com
Fri Jun 21 22:44:23 CEST 2013


Matt D wrote:
> [Ramit P wrote:]
> > When you open a file the data should be written to that. If you want to
> > move existing data from logfile.txt into user opened file then you need
> > to read logfile.txt and then write it to the user opened file. To make
> > your life simpler, either pass in the file path or open the file save
> > dialog on __init__.
> >
> >
> > ~Ramit
> >
> I got so frustrated try to figure a way to use the logfile.txt that I
> changed how i log. first i name an array:
> 
> class TrafficPane(wx.Panel):
>     # Initializer
>     # the class constructor
>     def __init__(self, parent, msgq):
>         wx.Panel.__init__(self, parent)
>         self.msgq = msgq
>         #create the array to put the traffic data in
>         self.log_array = []
> 
> Then this is how the array gets into the file the user chooses:
> 
>   # openfile defined to start FileDialog
>     def openFile(self, evt):
>         with wx.FileDialog(self, "Choose a file", os.getcwd(), "",
>                             "*.txt*", wx.OPEN) as dlg:
>             if dlg.ShowModal() == wx.ID_OK:
>                 path = dlg.GetPath()
>                 #mypath = os.path.basename(path)
>                 mypath = os.path.abspath(path)
>                 f = open(mypath, "rw+")

Why are you opening the file in "rw+"? 

>                 f.writelines(self.log_array)

You should really switch to the "with open() as f:" idiom I keep showing 
you. This will automatically close the file for you.

Also note that your file is only getting written once. You should
probably clear log_array and change the file mode back to append.

> 
> And this is how i get the TextCtrl values into the array:
> 
> def update(self, field_values):
>         next_line = ""
>         #logger code---------------
>         #  first new line
>         #self.logfile.write('\n')
>         #  date and time
>         #self.logfile.write('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S",
> localtime()))))
>         next_line += (str(strftime("%Y-%m-%d %H:%M:%S", localtime())))
>         #  loop through each of the TextCtrl objects
>         for k,v in self.fields.items():
>             #  get the value of the current TextCtrl field
>             f = field_values.get(k, None)
>             if f:
>                 #  output the value with trailing comma
>                 #self.logfile.write('%s,'%(str(f)))
>                 next_line += (str(f) + ',')
>         log_array.append(next_line)
>         #end logger code----------
> 
> Its running right now.  I haven't had the opportunity to test if it
> works so im keeping my fingers crossed.

This is an inefficient string concatenation. It can take large amounts
of memory and time. 

next_line += (str(f) + ',')

You can use str.join or use the csv module (which I recommend as it
will escape the delimeter (eg. commas ) if it shows up in the data ).
I have sent an example of the csv module already. Also note that
your order of the dictionary is not guaranteed so your data
may end up out of order after each run. 

'hi', 1 , 5423
4255, 'hi', 2
# instead of
1, 'hi', 5423
2, 'hi', 4255

# A str.join example 
next_line = []
for key in sorted( self.fields ):
    f = field_values.get(k, None)
    if f:
        next_line.append(str(f))
line = ', '.join(next_line)
log_array.append(line)


~Ramit


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  


More information about the Tutor mailing list