我们如何使用julia一次读取一个.txt文件的每个字符?

时间:2018-09-11 17:27:27

标签: file io character julia

我正在尝试与Julia一起浏览.txt文件,并且程序读取文件时,我必须能够查看每个字符。我在Julia Docs页面上发现的很少是如何逐行阅读的。我知道基本设置应该是这样的

file = open("testfile.txt","r");
while !eof(file)
    //look at each character and store it to a variable 

一旦将其存储到变量中,我就知道如何操作它,但是我不知道如何将其放入变量存储中。

1 个答案:

答案 0 :(得分:8)

像这样使用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文件。