欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Julia: 1.0读取文本文件

程序员文章站 2022-04-28 09:22:53
...
# 有如下数据
1,2
3,4
5,6
7,8
9,10

# 说明,本例代码在julia1.0上测试通过
# 直接用数组读取
using DelimitedFiles
a = readdlm("123.txt", ',')  # 数据之间用英文逗号隔开,注意readdlm中是单引号
# a = readdlm("123.txt")  # 读取用空格分割的数据
println(a)
for i in 1:size(a,1)
    println(a[i,:])
end


# 用循环读取
n = 5
a = zeros(n); b = zeros(n)

io = open("123.txt", "r")
for i in 1:n
    str = readline(io)
    str = split(str,",")
    # str = split(str," ")  # 用一个空格分割数据
    a[i] = parse(Float64, str[1]); b[i] = parse(Float64, str[2])
    println(a[i], "  ", b[i])
end
close(io)


# 如果文本中只有一行数据,且有其他字符
100 200 300 # this is comment
using DelimitedFiles
a, b, c = readdlm("123.txt")  
println(a," ", b, " ", c)

# 如果这一行数据被逗号分开
100, 200, 300, # this is comment
using DelimitedFiles
a, b, c = readdlm("123.txt", ',') 
println(a," ", b, " ", c)

# 还有要注意的一点,readdlm读取的变量与文本中数据变量一致
# 而readline读取得到的数据类型为字符串类型
相关标签: julia