1
$\begingroup$

I have a nested list that I use Put[mylist, file] to write to a file. I would then like to then append to this nested list some values and add them to the file.

How can I do this without reading the whole file, appending to the list with join, and then writing the list back to the file?

My list looks like

element = {"TimeStamp", "140927_1716_23"}, {"Atom Number", 
  621543.}, {"Atom Number Error", 4720.7}, {"Centre Ioffe(mm)", 
  6.66745}, {"Centre Ioffe Error(mm)", 
  0.0052631}, {"Centre UpDown(mm)", 
  1.17768}, {"Centre UpDown Error(mm)", 
  0.00318682}, {"FWHM Ioffe(mm)", 1.68306}, {"FWHM Ioffe Error(mm)", 
  0.0132298}, {"FWHM UpDown(mm)", 1.29802}, {"FWHM UpDown Error(mm)", 
  0.00842762}, {"Background Ioffe", 
  78.9332}, {"Background Ioffe Error", 8.77044}, {"Background UpDown",
   255.325}, {"Background UpDown Error", 11.5685}, {"Trap Type", 
  "Magnetic Trap"}, {"MOT_Loading_Time", 
  10000.}, {"Magnetic_Hold_Time", 50.75}, {"Time_Of_Flight", 
  6.}, {"Exposure_Time", 0.45}

mylist = {element1, element2, ..., elementN}

myList is Put into a file. I would like to join more elements into the file (without reading it all joining and rewriting the file).

mylist = {element1, element2, ..., elementN, elementN+1}
$\endgroup$
2
  • $\begingroup$ Maybe PutAppend? $\endgroup$
    – kglr
    Nov 4 '14 at 10:11
  • $\begingroup$ PutAppend just adds to the file, but won't join the new element to the list. $\endgroup$
    – labjunky
    Nov 4 '14 at 10:12
1
$\begingroup$

You should re-consider the format you use for storing the data. From the question it is clear that the file is intended to be imported by Mathematica. Then why do not use a line-by-line format and then import the file using ReadList? You can append the elements of myList one-by-one to the file using PutAppend. Then you can use ReadList to get them all back at once as complete myList. ReadList has excellent performance and is intended to be used exactly for such purposes.

$\endgroup$
0
$\begingroup$
SetDirectory[NotebookDirectory[]];
element1 = {a, b, c};
mylist = {element1};
Put[mylist, "mylist.txt"];
element2 = {d, e, f};
mylist = Append[mylist, element2];
Put[mylist, "mylist.txt"];

You need to save this example before running because of the NotebookDirectory function.

$\endgroup$
1
  • $\begingroup$ This writes the whole list every time after its appended too. It might not be very efficient for large lists. $\endgroup$
    – labjunky
    Nov 5 '14 at 3:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.