我们如何使用julia一次读取一个.txt文件的每个字符? [英] How do we use julia to read through each character of a .txt file, one at a time?
问题描述
我正在尝试使用Julia来浏览.txt文件,并且程序读取文件时,我必须能够查看每个字符.我在Julia Docs页面上发现的很少是如何逐行阅读的.我知道基本设置应该是这样的
I am trying to go through a .txt file with Julia, and I need to be able to look at every character as the program reads through the file. What little I have found on the Julia Docs page is how to read line by line. I know that the basic set up should be something like this
file = open("testfile.txt","r");
while !eof(file)
//look at each character and store it to a variable
一旦将其存储到变量中,我就知道如何操作它,但是我不知道如何将其放入变量存储中.
Once it is stored into a variable I know how to manipulate it, but I can't figure out how to get it into the variable storage.
推荐答案
像这样使用read
函数:
file = open("testfile.txt","r")
while !eof(file)
c = read(file, Char)
# your stuff
end
close(file)
这将使用UTF-8逐个字符地读取它.
This will read it character by character using UTF-8.
如果要逐字节读取,请使用:
If you want to read it byte by byte then use:
file = open("testfile.txt","r")
while !eof(file)
i = read(file, UInt8)
# your stuff
end
close(file)
请注意,您可以在离开文件时使用do
块自动关闭文件:
Note that you can use do
block to automatically close a file when you leave it:
open("testfile.txt","r") do file
while !eof(file)
i = read(file, UInt8)
# your stuff
end
end
对于更完整的示例,您可能希望查看例如在此功能 https://github.com/bkamins/使用模式read(io, Char)
解析CSV文件的Nanocsv.jl/blob/master/src/csvreader.jl#L1 .
For a more complete example you might want to have look e.g. at this function https://github.com/bkamins/Nanocsv.jl/blob/master/src/csvreader.jl#L1 that uses pattern read(io, Char)
to parse CSV files.
这篇关于我们如何使用julia一次读取一个.txt文件的每个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!