Thien Nguyen Huynh
Thien Nguyen Huynh

Reputation: 33

Julia - Read every 358 lines of a file

I am working on some calculations for my crystals. My file has around 15,750,756 x-y-z coordinates in string format. I want to read the information in every 358 line, but I don't know how to do it.

I only know this code. But It will read every single line instead of every 358 line.

file = open(trajectory_file_path)
for i in eachline(file)
#What to do here?
    append!(defect_positions,[split(i[4:end])] )
end
end
close(file)

Upvotes: 1

Views: 273

Answers (1)

JKHA
JKHA

Reputation: 1896

I suppose you have in a file test.csv the following lines :

1 2 3
4 5 6
...
100 101 102
...

with for example, more than 358 lines and the three values representing your x-y-z coordinates.

For reading every 358 lines and storing in the array defect_positions you could to the following:

function read_some_lines(filepath::String)

    defect_positions = Vector{Vector{SubString{String}}}(undef, 0)
    file = open(filepath)
    counter = 0
    for i in eachline(file)
        if (counter%358 == 0)
            push!(defect_positions,split(i))
        end
        counter += 1
    end
    close(file)
    defect_positions
end

read_some_lines("./test.csv")

You could want to convert the strings representing your coordinates into Integers or Float64 for instance.

function read_some_lines(filepath::String)

    defect_positions = Vector{Vector{Int}}(undef, 0)
    file = open(filepath)
    counter = 0
    for i in eachline(file)
        if (counter%358 == 0)
            push!(defect_positions,parse.(Int,split(i)))
        end
        counter += 1
    end
    close(file)
    defect_positions
end

read_some_lines("./test.csv")

Upvotes: 2

Related Questions