Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Utility method for writing and reading from a multi-line string #750

Closed
pdeffebach opened this issue Oct 11, 2020 · 6 comments
Closed

Utility method for writing and reading from a multi-line string #750

pdeffebach opened this issue Oct 11, 2020 · 6 comments

Comments

@pdeffebach
Copy link

One thing that might be nice for Discourse posts and debugging in general is some sort of way to use CSV.jl to print to a multi-line string and then have CSV read such a string back into a data frame.

I was playing around with this just now and couldn't find the right combination of CSV.write(io), show(df, MIME("text/csv"), df) and take!(io) for this to work.

@quinnj
Copy link
Member

quinnj commented Oct 12, 2020

It's pretty straightforward using IOBuffer, like:

io = IOBuffer()
CSV.write(io, df)
seekstart(io)
df2 = CSV.read(io, DataFrame)

@quinnj quinnj closed this as completed Oct 12, 2020
@pdeffebach
Copy link
Author

Sorry, I mean a way that a user can copy a multi-line string of their data into a discourse post, then I can read it into CSV from that.

That should be easy to do, right?

@quinnj
Copy link
Member

quinnj commented Oct 12, 2020

Oh, yeah, probably something like:

julia> df = DataFrame(a=[1,2,3], b=[3.4, 5.6, 7.9], c=["hey","there","buddy"])
3×3 DataFrame
│ Row │ a     │ b       │ c      │
│     │ Int64 │ Float64 │ String │
├─────┼───────┼─────────┼────────┤
│ 113.4     │ hey    │
│ 225.6     │ there  │
│ 337.9     │ buddy  │

julia> io = IOBuffer()
IOBuffer(data=UInt8[...], readable=true, writable=true, seekable=true, append=false, size=0, maxsize=Inf, ptr=1, mark=-1)

julia> CSV.write(io, df)
IOBuffer(data=UInt8[...], readable=true, writable=true, seekable=true, append=false, size=40, maxsize=Inf, ptr=41, mark=-1)

julia> println(String(take!(io)))
a,b,c
1,3.4,hey
2,5.6,there
3,7.9,buddy

@pdeffebach
Copy link
Author

But then, how do I read that into a data frame after it's printed?

@quinnj
Copy link
Member

quinnj commented Oct 12, 2020

df = CSV.read(IOBuffer("""
a,b,c
1,3.4,hey
2,5.6,there
3,7.9,buddy
"""), DataFrame)

@pdeffebach
Copy link
Author

Thanks! I will start recommending people do this on Discourse.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants