# I would like to monitor a file sieve.txt and take its contents in dynamic

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"]

Dynamic[srv]


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

• Does it help: mathematica.stackexchange.com/a/138433/5478 ?
– Kuba
Nov 25 '20 at 8:23
• Try e.g.: Dynamic[Refresh[t = Get["d:/tmp/t.txt"], UpdateInterval -> 1]] Nov 25 '20 at 8:32

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

Clear[monitorFile]
monitorFile[
Dynamic[contents_],
file_String?FileExistsQ,
importFunction : _ : Import,
formatFun : _ : Identity
] := DynamicModule[{
modificationDate,
display = ""
},
DynamicWrapper[
DynamicWrapper[
Column[{
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.

# Update

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

Dynamic[Refresh[Import["sieve.txt", "Data"], UpdateInterval -> 1]]

• 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.
– Kuba
Nov 25 '20 at 8:39
• Perfect. I’ll test it. Nov 25 '20 at 8:43
• @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. Nov 25 '20 at 9:50