Writing in a file ? Julia language

Viewed 954

Here’s an overview of my file :

[2020/06/18 17:19:25] Window closed --> OptionDialog = 'Waiting Dialog - Session restore'  -->  frame = 'DataManager' 
[2020/06/18 17:19:40] Window opened -->  frame = 'DataManager' 
[2020/06/18 17:19:40] MB1  --> Menu item = [Toolbox]  -->  frame = 'DataManager' 
[2020/06/18 17:19:42] MB1  --> Menu item = [2G&R Synthesis toolbox, Toolbox]  --> Popup Menu -->  frame = 'DataManager' 
[2020/06/18 17:19:42] Window opened -->  frame = 'ToolBox' 
[2020/06/18 17:19:42] Window gained focus -->  frame = 'ToolBox' 

I would like to retrieve only the lines with the substring “Window” just after the dates and then write them in a new text file. Here's what I have done so far :

file = open("Test2.txt") do file
    f = readlines(file)
    for line in f
      if line[23:28]== "Window"
         open("t.txt","w") do file
         write(file,line)
         end
      end
   end
end

My problem is that only the last line containing "Window" from the first file is written to the new file. For exemple here it would be :

[2020/06/18 17:19:42] Window gained focus -->  frame = 'ToolBox'

How do I make sure that ALL the lines containing "Window" are written to the new file?

Thank you in advance for your answers,

Valentine

1 Answers

First, I think you should replace write(file, line) to println(file, line) as otherwise newline will not be printed.

There are several solutions to your problem:

The simplest is to change "w" to "a" in open("t.txt","w"); the problem with it is that if the file exists new lines will get appended to it

Normally you would open the file for writing only once and use something like:

open("Test2.txt") do file
    f = readlines(file)
    open("t.txt", "w") do file2
        for line in f
            if line[23:28] == "Window"
                println(file2, line)
            end
        end
    end
end

Finally you do not need to use readlines as it will eat-up a lot of memory for large files, and can process the file line by line like this:

open("t.txt","w") do file2
    for line in eachline("Test2.txt")
        if line[23:28] == "Window"
            println(file2, line)
        end
    end
end

Also note that the check line[23:28] == "Window" is only correct if you know you have only ASCII characters in your file and you are sure that your lines are long enough to have 28 characters (or an error will be thrown in your code if it does not have that many characters). If you were not sure that this is the case better use:

startswith(chop(s, head=22, tail=0), "Window")
Related