CSV.read() 函数也可用于读取分隔文件。 CSV.read() 相对于readdlm() 的优势在于CSV.read() 对于大文件来说要快得多。例如,要阅读以下内容,
julia> file =
"""
23 12 13 22
15 61 17 10
1 0 11 12
"""
代码是,
julia> CSV.read(IOBuffer(file),delim=" ",ignorerepeated=true,header=false)
3×4 DataFrames.DataFrame
│ Row │ Column1 │ Column2 │ Column3 │ Column4 │
│ │ Int64 │ Int64 │ Int64 │ Int64 │
├─────┼─────────┼─────────┼─────────┼─────────┤
│ 1 │ 23 │ 12 │ 13 │ 22 │
│ 2 │ 15 │ 61 │ 17 │ 10 │
│ 3 │ 1 │ 0 │ 11 │ 12 │
对于小文件,readdlm() 更快。
julia> using BenchmarkTools
julia> @btime CSV.read(IOBuffer(file),delim=" ",ignorerepeated=true,header=false);
68.197 μs (185 allocations: 14.80 KiB)
julia> @btime readdlm(IOBuffer(file));
2.465 μs (20 allocations: 40.70 KiB)
但对于较大的文件,CSV.read() 更快更高效。
julia> @btime CSV.read(IOBuffer(file^100000),delim=" ",ignorerepeated=true,header=false);
32.027 ms (230 allocations: 3.26 MiB)
julia> @btime readdlm(IOBuffer(file^100000));
142.187 ms (3600025 allocations: 116.44 MiB)
可以转换为数组,
julia> dffile = CSV.read(IOBuffer(file),delim=" ",ignorerepeated=true,header=false);
julia> convert(Matrix, dffile)
3×4 Array{Int64,2}:
23 12 13 22
15 61 17 10
1 0 11 12
可以进行许多其他自定义以读取不同类型的文件,详情请参阅documentation。