I would like to monitor a file sieve.txt and take its contents in dynamic. :I did this but Dynamic does not work in this case:

Dynamic[srv=Import[C:\\maths\\sieve.txt, "Data"]


Is there a function or a small program that can do this. Thank you.


This function will monitor the file modification timestamp to determine if the contents need to be imported again:

  importFunction : _ : Import, 
  formatFun : _ : Identity
] := DynamicModule[{
   display = ""
      Dynamic[modificationDate, TrackedSymbols :> {modificationDate}],
      Dynamic[display, TrackedSymbols :> {display}]
    }, Alignment -> Left]
    modificationDate;(* This triggers the update *)
    If[ DateObjectQ[modificationDate],
        contents = importFunction[file];
        display = formatFun[contents]
        contents = display = Missing[]
    SynchronousUpdating -> False,
    TrackedSymbols :> {modificationDate}
   modificationDate = Quiet @ Information[File[file], "LastModificationDate"],
   SynchronousUpdating -> True,
   UpdateInterval -> 1.

Example usage:

file = "table.txt";
Export[file, List /@ Range[5], "Table"];
monitorFile[Dynamic[x], file, Import[#, "Table"] &, Grid]

Note that I'm not 100% sure that Information[File[file], "LastModificationDate"] works on all operating systems since there are a number of different timestamps associated with files depending on the OS. You may have to look at Information[File[file], "Properties"] to see what property you need to query.

Another thing to keep in mind is that Dynamics will only update when they need to be displayed, so you can't use this as a background file monitor. If that's what you need, you should look at ScheduledTask instead.


I made the function more robust in the situation where the file gets deleted suddenly.

Dynamic[Refresh[Import["sieve.txt", "Data"], UpdateInterval -> 1]]
  • 4
    $\begingroup$ This tries to import file each second, could be problematic for larger files. File last modification date would be better but I don't remember how fast it is. $\endgroup$
    – Kuba
    Nov 25 '20 at 8:39
  • $\begingroup$ Perfect. I’ll test it. $\endgroup$ Nov 25 '20 at 8:43
  • 1
    $\begingroup$ @Kuba Thanks, you, your solution is complete mathematica.stackexchange.com/a/138433/5478 and suits me perfectly, because the file watcher will track the size of the file and when it changes automatically reload the contents. $\endgroup$ Nov 25 '20 at 9:50

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.