Mathematica Asked by Reda.Kebbaj on December 13, 2020
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:mathssieve.txt, "Data"]
Dynamic[srv]
Is there a function or a small program that can do this.
Thank you.
Dynamic[Refresh[Import["sieve.txt", "Data"], UpdateInterval -> 1]]
Answered by cvgmt on December 13, 2020
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 Dynamic
s 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.
Answered by Sjoerd Smit on December 13, 2020
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP