Saving Primes Number in a range to CSV

Hi all,

I want to save all prime numbers in certain range into CSV. But why it does not saved?

I am following this forum:

using Primes, CSV

CSV.write("./out.csv", (p = primes(1,1000000)))

CSV.write only accept Tables.jl interface input (see doc).

So it can be fixed by convert the prime vector to a table (alternatively, DataFrames also works):

using Primes, CSV, Tables
CSV.write("./out.csv", Tables.table(primes(1,1000000)))
1 Like

It works great. Thanks

That’s a solution, but I don’t think it should be the solution.

It’s correct that CSV.write requires a Tables compatible object, but that doesn’t mean you actually need Tables - a NamedTuple is a valid table and built into base.

Your problem in translating my Stackoverflow answer to your case is that to construct a one element tuple you need to append a comma before the closing parentheses, consider:

julia> (x = rand(5))
5-element Vector{Float64}:
 0.6238084279345859
 0.8932712676662397
 0.36832615201955377
 0.9091819412601923
 0.5210877983924257

julia> (x = rand(5),)
(x = [0.04347875708971949, 0.1589617604772473, 0.8344142933023203, 0.632009784788371, 0.5841220686173417],)

in the first case, the brackets don’t actually do anything, while in the second case they construct a NamedTuple. So you should do CSV.write("./out.csv", (p = primes(10_000), )) and things will work out without any extra dependencies.

The reason you need the extra comma is that we don’t want simple expressions wrapped in brackets to produce tuples, consider:

julia> (5 - 3)*6
12

julia> (5 - 3,)*6
ERROR: MethodError: no method matching *(::Tuple{Int64}, ::Int64)
3 Likes

Yes, it works too without extra dependency… I thought I do not need ,