提问人:JKHA 提问时间:12/15/2021 更新时间:12/15/2021 访问量:122
在 Julia 中切碎文件
Chop a file in Julia
问:
我在 Julia 中打开了一个文件:
output_file = open(path_to_file, "a")
我想砍掉文件的最后六个字符。
我以为我可以用 ,即,但似乎它只适用于类型,而不适用于 .我该怎么办?chop
chop(output_file; tail = 6)
String
IOStream
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
我是IOStream的新手,今天发现了它们。
答:
2赞
JKHA
12/15/2021
#1
我在这里找到了我想要的东西,它适应了我的问题:
(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)
也许我的问题可以标记为重复!
2赞
Sundar R
12/15/2021
#2
在您的情况下,由于您正在对文件末尾执行一次写入操作,并且不执行任何进一步的读取或其他操作,因此还可以按如下方式就地编辑文件:
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
这将覆盖我们希望用等长的空格字符截断的文本。我不确定是否有办法简单地删除该行(而不是用 )。' '
评论
0赞
JKHA
12/15/2021
谢谢!比我的解决方案更好:D是的,能够删除字符而不是用空格替换它们会很有趣。
评论