【问题标题】:How to edit a line of a file in julia?如何在Julia中编辑文件的一行?
【发布时间】:2019-09-19 15:03:45
【问题描述】:

我可以读取一个文件并根据这样的谓词找到一个特殊的行

open(file, read=true, write=true, append=true) do io
    for line in eachline(io)
        if predicate(line)
            new_line = modifier(line)
            # how to replace the line with new_line in the file now?
        end
    end
end

但是我现在如何更改文件中的内容呢?

【问题讨论】:

    标签: file io julia


    【解决方案1】:

    一般来说,您不能就地修改文件(对于 julia 以外的语言也是如此),因为添加或删除字符会改变后面所有内容的位置(文件只是一个长字符串字节)。

    所以你可以

    1. 读入整个文件,更改您要更改的内容,然后将整个文件写入同一位置
    2. 逐行读取,写入新位置,然后将新文件复制到旧位置

    如果您有非常大的文件,后者可能会更好(因此您不必将整个内容存储在内存中)。您已经获得了大部分代码,这只是creating a temp 文件的问题,然后在最后复制回原始路径。比如:

    (tmppath, tmpio) = mktemp()
    open(file) do io
        for line in eachline(io, keep=true) # keep so the new line isn't chomped
            if predicate(line)
                line = modifier(line)
            end
            write(tmpio, line)
        end
    end
    close(tmpio)
    mv(tmppath, file, force=true)
    

    注意:如果这是在全局范围内(例如,不在函数内),您可能必须将 global 放在 tmpio 前面的 do 块内。或者,将整个内容包裹在 let 中。 See here.

    【讨论】:

    • 这需要mv(tmppath, file, force = true),因为file 已经存在。
    • close(tmpio) 之前的mv
    • 另外write(tmpio, line) 应该是write(tmpio, line * "\n")eachline(io) 应该是eachline(io, keep=true)。否则,所有行都连接起来。
    • @Dominique :+1: 固定
    猜你喜欢
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多