首页 > 解决方案 > 我们如何使用 julia 一次读取一个 .txt 文件的每个字符?

问题描述

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

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

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

标签: fileiocharacterjulia

解决方案


使用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在离开时使用 block 自动关闭文件:

open("testfile.txt","r") do file
    while !eof(file)
        i = read(file, UInt8)
        # your stuff
    end
end

对于更完整的示例,您可能希望查看例如使用模式解析 CSV 文件的此函数https://github.com/bkamins/Nanocsv.jl/blob/master/src/csvreader.jl#L1 。read(io, Char)


推荐阅读