File 如何在julia中编辑文件的行?

File 如何在julia中编辑文件的行?,file,io,julia,File,Io,Julia,我可以读取一个文件并根据这样的谓词找到一个特殊的行 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?

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

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

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

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

所以你可以

  • 读入整个文件,更改要更改的内容,然后将整个文件写入同一位置
  • 逐行读取、写入新位置,然后将新文件复制到旧位置
  • 如果你有非常大的文件,后者可能更好(这样你就不必把整个文件都存储在内存中)。您已经获得了大部分代码,这只是一个文件问题,然后在最后复制回原始路径。比如:

    (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
    将整个过程包装起来

    这需要
    mv(tmppath,file,force=true)
    ,因为
    file
    已经存在。而且
    mv
    之前的
    close(tmpio)
    也可以
    write(tmpio,line)
    应该是
    write(tmpio,line*“\n”)
    或者
    eachline(io)
    应该是
    eachline(io,keep=true)
    。否则,所有行都被连接。@Dominique:+1:已修复