我正在尝试使用Julia处理一个.txt文件,并且需要能够查看程序读取文件时的每个字符。但是在Julia文档页面上,我所找到的关于此问题的信息都只介绍了如何按行读取。我知道基本设置应该像这样:
file = open("testfile.txt","r");
while !eof(file)
//look at each character and store it to a variable
一旦存储到变量中,我知道如何操作它,但我无法弄清楚如何将其存储到变量存储中。
使用read
函数的方法如下:
file = open("testfile.txt","r")
while !eof(file)
c = read(file, Char)
# your stuff
end
close(file)
这将使用UTF-8逐个字符地读取它。
如果您想按字节读取,请使用:
file = open("testfile.txt","r")
while !eof(file)
i = read(file, UInt8)
# your stuff
end
close(file)
请注意,您可以使用do
块在离开文件时自动关闭它:open("testfile.txt","r") do file
while !eof(file)
i = read(file, UInt8)
# your stuff
end
end
如果您想查看更完整的示例,可以查看此函数https://github.com/bkamins/Nanocsv.jl/blob/master/src/csvreader.jl#L1,该函数使用模式read(io, Char)
解析CSV文件。