|
95 | 95 | function fileio_save(s::FileIO.Stream{FileIO.format"TSV"}, data; delim='\t', quotechar='"', escapechar='"', nastring="NA", header=true) |
96 | 96 | return _save(s.io, data, delim=delim, quotechar=quotechar, escapechar=escapechar, nastring=nastring, header=header) |
97 | 97 | end |
| 98 | + |
| 99 | +# |
| 100 | +# Streaming version writes header (if any) on first call, then appends on subsequent calls. |
| 101 | +# |
| 102 | +const CSV_or_TSV = Union{FileIO.format"CSV", FileIO.format"TSV"} |
| 103 | + |
| 104 | +_delim(T) = T <: FileIO.format"CSV" ? ',' : '\t' |
| 105 | + |
| 106 | +mutable struct CSVFileSaveStream{T} |
| 107 | + io::T |
| 108 | + first_data_written::Bool |
| 109 | + delim::Char |
| 110 | + quotechar::Char |
| 111 | + escapechar::Char |
| 112 | + nastring::AbstractString |
| 113 | + header::Bool |
| 114 | +end |
| 115 | + |
| 116 | +function fileio_savestreaming(f::FileIO.File{T}, data=nothing; delim=_delim(T), quotechar='"', escapechar='"', nastring="NA", |
| 117 | + header=true) where T <: CSV_or_TSV |
| 118 | + io = open(f.filename, "w") |
| 119 | + |
| 120 | + if data!==nothing |
| 121 | + _save(io, data; delim=delim, quotechar=quotechar, escapechar=escapechar, nastring=nastring, header=header) |
| 122 | + end |
| 123 | + |
| 124 | + return CSVFileSaveStream(io, data!==nothing, delim, quotechar, escapechar, nastring, header) |
| 125 | +end |
| 126 | + |
| 127 | +function fileio_savestreaming(s::FileIO.Stream{T}, data=nothing; delim=_delim(T), quotechar='"', escapechar='"', nastring="NA", |
| 128 | + header=false) where T <: CSV_or_TSV |
| 129 | + |
| 130 | + if data!==nothing |
| 131 | + _save(s.io, data; delim=delim, quotechar=quotechar, escapechar=escapechar, nastring=nastring, header=header) |
| 132 | + end |
| 133 | + |
| 134 | + return CSVFileSaveStream(s.io, data!==nothing, delim, quotechar, escapechar, nastring, header) |
| 135 | +end |
| 136 | + |
| 137 | +function Base.write(s::CSVFileSaveStream, data) |
| 138 | + _save(s.io, data; delim=s.delim, quotechar=s.quotechar, escapechar=s.escapechar, nastring=s.nastring, header=s.first_data_written ? false : header) |
| 139 | +end |
| 140 | + |
| 141 | +function Base.close(s::CSVFileSaveStream) |
| 142 | + close(s.io) |
| 143 | +end |
0 commit comments