file - 我们如何使用 julia 一次读取一个 .txt 文件的每个字符?
问题描述
我正在尝试使用 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
在离开时使用 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)
推荐阅读
- kubernetes - 在 EKS 中以不受支持的版本创建集群
- azure - 如何自动启用新 Azure VM 的日志记录?
- python - 合并两列并使用熊猫库创建新列
- amazon-web-services - 如何创建 AWS 托管 KMS 密钥
- python - Kubernetes:1 Pod 和 3 Pod 的性能没有区别?
- asp.net-core - 如何使用 SumAsync 计算 Asp.Net 核心中自定义值对象的总和
- node.js - GraphQL 订阅成功握手后收不到消息
- python - 在我没有 root 访问权限的服务器中的 docker 映像中运行 python 代码
- kubernetes - 如何获取 GKE fluentbit 相关错误的详细信息?
- r - R-highcharter中平行图中的颜色y轴