写入文件?朱莉娅语言

Val*_*AND 4 file julia

这是我的文件的概述:

[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' 
Run Code Online (Sandbox Code Playgroud)

我只想检索日期之后带有子字符串“Window”的行,然后将它们写入新的文本文件中。这是我到目前为止所做的:

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

Run Code Online (Sandbox Code Playgroud)

我的问题是只有第一个文件中包含“Window”的最后一行被写入新文件。例如这里将是:

[2020/06/18 17:19:42] Window gained focus -->  frame = 'ToolBox'
Run Code Online (Sandbox Code Playgroud)

如何确保所有包含“Window”的行都写入新文件?

预先感谢您的回答,

情人节

Bog*_*ski 5

首先,我认为您应该替换write(file, line)println(file, line) ,否则将不会打印换行符。

您的问题有几种解决方案:

最简单的就是变化"w",以"a"open("t.txt","w"); 它的问题是,如果文件存在,新行将被附加到它

通常你会打开文件只写一次并使用类似的东西:

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
Run Code Online (Sandbox Code Playgroud)

最后你不需要使用,readlines因为它会为大文件占用大量内存,并且可以像这样逐行处理文件:

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

另请注意,line[23:28] == "Window"只有当您知道文件中只有 ASCII 字符并且您确定您的行足够长以包含 28 个字符时,检查才正确人物)。如果您不确定是否是这种情况,最好使用:

startswith(chop(s, head=22, tail=0), "Window")
Run Code Online (Sandbox Code Playgroud)