Home > other >  Chop a file in Julia
Chop a file in Julia

Time:12-15

I have opened a file in Julia:

output_file = open(path_to_file, "a")

And I would like to chop the six last characters of the file. I thought I could do it with chop, i.e., chop(output_file; tail = 6) but it seems it only works with String type and not with IOStream. How should I do?

julia> rbothpoly(0, 1, [5], 2, 30, "html")
ERROR: MethodError: no method matching chop(::IOStream; tail=6)
Closest candidates are:
  chop(::AbstractString; head, tail) at strings/util.jl:164
Stacktrace:
 [1]
 [...] ERROR STACKTRACE [...]
 [3] top-level scope at REPL[37]:1

I am new to IOStream, discovering them today.

CodePudding user response:

I have found what I wanted here, which adapts in my problem to:

            (tmppath, tmpio) = mktemp()
            open(output_filename, "r") do io
                for line in eachline(io, keep=true) # keep so the new line isn't chomped
                    if line == "</pre>\n"
                        line = "\n"
                    end
                    write(tmpio, line)
                end
            end
            close(tmpio)
            mv(tmppath, output_filename, force=true)
            chmod(output_filename, 0o777)
            close(output_file)

Maybe my question could be marked as duplicate!

CodePudding user response:

In your case, because you're doing a single write to the end of the file and not doing any further read or other operations, you can also edit the file in-place like this:

function choppre(fname = "data/endinpre.html")
  linetodelete = "</pre>\n"
  linelength = length(linetodelete)
  open(fname, "r ") do f
    readuntil(f, linetodelete)
    seek(f, position(f) - linelength)
    write(f, " "^linelength)
  end
end

This overwrites the text we wish to chop off with an equal length of space characters. I'm not sure if there's a way to simply delete the line (instead of overwriting it with ' ').

  • Related