【问题标题】:Writing in a file ? Julia language写入文件?朱莉娅语言
【发布时间】:2023-03-14 21:33:01
【问题描述】:

这是我的文件的概述:

[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' 

我想只检索日期之后带有子字符串“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

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

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

如何确保ALL包含“Window”的行被写入新文件?

提前感谢您的回答,

情人节

【问题讨论】:

  • 看看函数eachline,它将减少您需要的代码量。
  • 我只是在写这个:)。并同意 - 这是一种首选方式,因为它不必将整个文件读入内存。

标签: file julia


【解决方案1】:

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

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

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

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

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

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

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

还请注意,检查 line[23:28] == "Window" 仅在您知道文件中只有 ASCII 字符并且您确定行长到足以包含 28 个字符时才正确(否则,如果您的代码中出现错误它没有那么多字符)。如果您不确定是否是这种情况,最好使用:

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

【讨论】:

    猜你喜欢
    • 2018-11-27
    • 1970-01-01
    • 2014-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-04
    • 2014-12-31
    • 2017-01-15
    相关资源
    最近更新 更多