Search code examples
stringjuliaiostreamchop

Chop a file in Julia


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.


Solution

  • 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 ' ').