我试图与Julia一起浏览.txt文件,并且程序读取文件时,我需要能够查看每个字符。我在Julia Docs页面上发现的很少是如何逐行阅读的。我知道基本设置应该是这样的
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文件。
关于file - 我们如何使用julia一次读取一个.txt文件的每个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52281241/