The csv module processes delimited text files: it can load them into tables in memory, or work through them in batches to filter rows, persist them to disk or send them to a kdb+ tickerplant or a DB Service. It infers the type of each column from a sample of rows, so you don't have to write the type string that 0: needs.
- Type inference by rules. The module types each column with an ordered list of numbered type rules.
infershows which rules matched and flags uncertain guesses, so you can check the types before you load. Thetypesoption overrides any of them. - Rule sets. The basic rules always run. They cover numbers, dates, times, timestamps, booleans, GUIDs, IP addresses and text. The
rulesoption switches on optional sets:`extendedadds guesses from plain digits such as20240115, and`financialadds capital markets formats such as bond prices in 32nds and checked instrument identifiers such as ISIN and OCC option symbols. A set is a group of rules behind one name that you switch on or off together. - Easy to add a domain. A rule set is one dictionary, with its rules, options, conversions and the columns it adds, and one line that registers it, so a new domain, such as currencies or commodities, is supported without touching the other sets. See Adding a rule set.
- Formats from real files. Thousands separators, currency and percent signs, decimal commas, ISO 8601 (the standard date and time format) timestamps with a time zone, Unix epochs, 12-hour times, and dates with the year last in either day and month order.
- Loading options. Pick the delimiter, columns and number of rows; trim padded text; treat placeholders such as
N/Aas nulls; merge a date column and a time column into one timestamp; and decode option symbols and futures codes into columns. - Batches. The
batchsizeoption processes a file too large for memory a batch at a time, with apostProcessfunction that filters, saves or publishes each batch. The types are inferred once and every conversion applies. - Bad values.
rejectslists the values that don't parse as the type of their column, and thestrictoption turns them into an error.
The examples load the module into the .csv namespace:
.csv:use`kx.csvcsv is a reserved keyword in q, so it can't be used as a name. Load the module under another name, such as c:use`kx.csv.
The examples read test/data/basic.csv, a 40-row file with a column of each common type.
Load the module and read a file. read infers the type of each column from a sample of rows, so there is no type string to write:
q).csv:use`kx.csv
q)f:`:test/data/basic.csv
q).csv.read[f;([nrows:3;columns:`id`price`sym`date`ts`active])]
id price sym date ts active
-------------------------------------------------------------
1 49.27 AAPL 2024.01.15 2024.01.15D09:30:00.123456789 1
2 61.7 MSFT 2024.01.16 2024.01.15D09:30:01.123456789 0
3 61.59 GOOG 2024.01.17 2024.01.15D09:30:02.123456789 1Check the types before a large load with infer. A type that is a guess is marked uncertain:
q)select column,qtype,uncertain from .csv.infer[f] where column in`id`price`sym`ymd
column qtype uncertain
----------------------
id J 0
price F 0
sym S 1
ymd J 0Change what you don't like. types sets a type for a column, and rules switches on more guesses: ymd holds dates written as 20240115, which the `extended rules read as dates:
q).csv.read[f;([types:([sym:"*"]);rules:`extended;columns:`id`sym`ymd;nrows:2])]
id sym ymd
--------------------
1 "AAPL" 2024.01.15
2 "MSFT" 2024.01.16Look around in a file with peek, which returns the first rows and rows from evenly spaced places, and find the values that don't fit the types with rejects. Set strict to make read signal them as an error:
q).csv.rejects[`:test/data/rejects.csv;([sample:3])]
column row line text qtype
----------------------------------
price 3 5 "abc" F
when 3 5 "2024-13-45" D
q).csv.read[`:test/data/rejects.csv;([sample:3;strict:1b])]
'csv: 2 value(s) did not parse as the type of their column: price 1, when 1. Use rejects to list them.The same read also loads:
| To load | Write |
|---|---|
| a file too large for memory, a batch at a time | .csv.read[f;([batchsize:100000000;postProcess:{`trades upsert x;()}])] |
| several files as one table | .csv.read["trades/day*.csv"] |
| a gzip file | .csv.read`:trades.csv.gz |
| a page on the web | .csv.read["https://example.com/trades.csv"] |
| a file with titles, totals or comments | .csv.read[f;([skipRows:2;skipFooter:1;comment:"#"])] |
The rest of this reference describes each function and option. Quotes, line endings and encodings are in File format.
| Function | Description |
|---|---|
read |
Load a file into a table |
infer |
Return the inferred type of each column, with the evidence |
peek |
Return the rows that infer samples, to look around in a file |
rejects |
Return the values that load as null though they hold text |
defaults |
The default options (a dictionary, not a function) |
read, infer, peek and rejects are variadic: they take a file, and optionally either a delimiter or an options dictionary. As with any variadic function, a call with fewer arguments runs rather than projects.
.csv.read[file]
.csv.read[file; delimiter]
.csv.read[file; options]Where
fileis a file symbol such as`:data.csv, a plain symbol, or a string. The last part of the path can be a pattern that matches several files. Anhttp://orhttps://string is a URL. A gzip file is unzipped, see Compressed filesdelimiteris a char atom, such as"|"or"\t"optionsis a dictionary of options
returns a table with one column per column of the file, or what the postProcess option makes of it. To set the delimiter together with other options, use the delimiter option: .csv.read[file;([delimiter:"|";nrows:10])].
Column names come from the header, cleaned up with .Q.id after the characters that a name can't hold are dropped. The rules, in order:
- Only ASCII letters, digits and
_are kept:Sale ConditionbecomesSaleCondition, andnaïvebecomesnave, as the bytes of a non-ASCII character are dropped. A byte order mark at the start of the file is not part of the first name. - A name that is empty after that becomes
a. A name that doesn't start with a letter gets anain front:1becomesa1, and_becomesa_. - A name that clashes with a q keyword gets a
1suffix:typebecomestype1. - Two names that are the same after cleaning, such as
a banda-b, or a repeated name, are made different with a1suffix, added again until the name is new: the headerx,x1,xgivesx,x1andx11. Case is kept, soxandXare different names. - Without a header, the columns are named
col1,col2, and so on.
Use these names in types, columns, formats, merge and expand, and expect them in the result of infer. The header can be any width, and a quoted name can contain the delimiter.
The names option sets the names yourself:
- A list names every column, by position, and has one name for each column of the file, else
readsignals an error. It works with and without a header: withheader:1bthe header line is not a row, and the names of the list replace its names; withheader:0bthe first line is data, as always, and the list names its columns. - A dictionary of old name to new name renames only the columns you give, and the others keep their cleaned names. The old names are those above, such as
col1without a header. - The names are yours, so they are not cleaned. A name that
.Q.idwould change, such as a q keyword (type),i, an empty name or one with a space, signals an error, and so do two columns with the same name. A rename can't take the name of another column either. - They are the names of the call.
types,columns,formats,merge,expandandfileColumnuse the new names, and so doinfer,peekandrejects. The header of a file is not checked against the list, so a list also hides a header that changes from one file to the next.
q).csv.read[`:prices.csv;([header:0b;names:`time`sym`px])]
q).csv.read[`:prices.csv;([names:([SalePrice:`px;TradeTime:`time])])]q)f:`:test/data/basic.csv
q).csv.read[f;([nrows:3;columns:`id`price`sym`date`ts`active])]
id price sym date ts active
-------------------------------------------------------------
1 49.27 AAPL 2024.01.15 2024.01.15D09:30:00.123456789 1
2 61.7 MSFT 2024.01.16 2024.01.15D09:30:01.123456789 0
3 61.59 GOOG 2024.01.17 2024.01.15D09:30:02.123456789 1
q)meta .csv.read f
c | t f a
------| -----
id | j
price | f
qty | j
sym | s
name | C
date | d
time | t
ts | p
flag | b
active| b
note | C
uid | g
empty | c
ymd | jFields in double quotes can contain the delimiter ("hello, world 1" in the note column). true, false, yes and no, in any case, load as booleans, and so do 0/1, t/f and y/n. A boolean column inferred from the single-character forms (0/1, t/f, y/n) loads with q's own boolean parser, so a true further down that column loads as 0b, which rejects and strict find. Lines can end in \n or \r\n.
Pass the delimiter or override an inferred type:
q).csv.read[`:trades.psv;"|"]
q).csv.read[f;([types:([id:"J";ymd:"D"])])] / id as long, ymd as date
q).csv.read[f;([types:([name:" "])])] / skip the name column
q).csv.read[`:noheader.csv;([header:0b])] / columns col1..colN!!! note "Inference reads a sample"
The types come from `sample` rows (5555 by default): the first rows, and blocks of rows from nine evenly spaced places in the rest of the file, so a file sorted by one column is not judged by its first values alone. A value outside the sample that does not parse as the inferred type loads as null, and `0:` does not report it. Set `sample` to `0W` to infer from the whole file, or fix the type with `types`. The sample is taken from the whole file, apart from the lines that `skipRows`, `skipFooter` and `comment` skip: `nrows` doesn't limit it, so inference can read rows that `read` doesn't load. With [a pattern](#several-files), `0W` is every row of every matching file, and any other `sample` is spread over up to ten of the files.
Integers load as longs and decimals as floats, as a sample can't tell how large the other values are. The [`frugal`](#options) option narrows them to the smallest type that holds the sampled values, which saves memory at the risk of nulls.
The default sample is enough for most files. To make sure of the types of a file:
1. Increase `sample`, for example to `55555`. A larger sample is more likely to meet a rare value, and inference stays fast, as it reads only the sampled rows.
1. Call [`rejects`](#rejects). It checks every value that `read` would load, so it finds what any sample missed, such as a column that holds only `0` in the sample and letters further down. To make `read` signal an error on such values instead, set `strict`.
A column inferred as char, or as boolean, can also meet a value that doesn't fit, such as `true` in a column of single letters. A longer value in a char column loads as a blank char, and text that isn't a boolean loads as `0b`, so `rejects` and `strict` check these columns too.
The last part of the path, the file name, can be a pattern that matches several files, with the wildcards of like: * for any characters, ? for one character and [abc] for a set of characters. read loads the matching files of the directory, in order of name, and joins them into one table.
q).csv.read["trades/2024-01-*.csv"] / every day of January
q).csv.read["trades/day?.csv"] / day1.csv ... day9.csv
q).csv.read["trades/day[13].csv"] / day1.csv and day3.csvA symbol literal can't hold the wildcards, as * ends it. Pass the pattern as a string, or as `$":trades/*.csv". A name without a wildcard, or a file that exists with that name, is that one file. To take every path as it is, even one with *, ? or [ in its name, set glob to 0b. Only the file name is a pattern, not the directories before it, and a pattern that matches no file signals an error.
All the files are one data set, so:
- Every file has the columns of the first one, in the same order, and
readsignals an error for a file that doesn't. - The types are inferred once, from a sample of rows taken from up to ten of the files, the first, the last and evenly spaced ones between (or from every file with
sampleset to0W). Thesamplerows are shared by the files: 5 rows over 3 files are 2, 2 and 1, and a sample of fewer rows than ten takes one file for each row, so the sample is never larger than asked for. So a column that holds3.5in one file only is a float in all of them.inferreturns the types in the same way. - The
fileColumnoption adds a symbol column, named by the option, that holds the file of each row, for example`:trades/day1.csv, so you can tell the files apart or filter on them, even inpostProcess. It is the last column, and its name can't be that of a column of the files. It works for a single file too. - Each file has its own header and its own
skipRows,skipFooterandcommentlines. Thenrowsoption counts the rows of all the files. postProcessis applied to the joined table. Withbatchsize, it is applied to each batch of each file, and a batch never holds rows of two files. See Loading a file in batches.rejectstakes one file, as it lists the lines of a file, and signals an error for a pattern that matches more than one.
A file that starts with http:// or https:// is a URL. read downloads it, and loads the page as it would a file. The URL is a string, as a symbol literal can't hold characters such as - and ?.
q)u:"https://football-data.co.uk/mmz4281/2425/E0.csv"
q)t:.csv.read[u;([dateOrder:`dmy;types:([Div:"S"])])]It works like .Q.hg and builds on the same function, so it uses the proxy settings of the environment, takes a user name and password in the URL, and uncompresses a gzipped page. It also does what .Q.hg doesn't: it signals an error for a status other than 200, instead of reading the error page as data, and it follows up to 5 redirects, to an absolute URL, a path on the same host or a path relative to the page.
- HTTPS needs SSL/TLS configured for the q process, for example
KX_SSL_CA_CERT_FILEset to a CA bundle. Without it, q signals an error. - The page is downloaded in full into memory, then to a temporary file with a random name in the directory of
TMPDIR,TEMPorTMP(/tmpwhen none is set), whichreaddeletes before it returns, also after an error. Every call downloads the page again, soinferthenreadis two downloads. To load a page more than once, download it with.Q.hgand save it to a file. - A URL is a single file, never a pattern:
globdoesn't apply to it. All the options work as for a file, includingbatchsize, which saves the memory of the loaded table but not that of the page. - With
fileColumn, the column holds the URL.
A gzip file loads like any other, with no option: .csv.read`:trades.csv.gz. read finds gzip by the first bytes of the file, not by its name, so it also unzips data.dat that holds gzip. A name such as data.tsv.gz has the delimiter of data.tsv. It works for URLs too, and in a pattern that matches gzip files and plain ones together.
read unzips the file with .Q.gz, which needs zlib in the q process, and loads the result from a temporary file that it deletes before it returns, also after an error. The options all work as for a plain file, and with fileColumn the column holds the name of the gzip file.
- The unzipping runs on one thread, unlike the load that follows, and takes much of the time for a large file. Unzip a file you load often once, and keep the plain one.
- Memory: the compressed and the unzipped bytes of one file are in memory together while it unzips. The temporary files of all the files of a pattern exist together until
readreturns, so there must be room for them in the temporary directory. - A file that is cut short signals an error, as the size that gzip files end with is checked against the size of the result. The same check refuses a file of several gzip members, such as
cat a.gz b.gz > c.gzor the blocks of abgzipfile. Unzip those first. - Other compression is not supported: bzip2, zstd, xz and zip files signal an error that names the format.
Files exported from other systems often have lines that are not part of the table: a title above the header, a total or a trailer record at the end, or notes. Three options leave them out:
q).csv.read[`:report.csv;([skipRows:2;skipFooter:1])] / 2 lines above the header, 1 at the end
q).csv.read[`:data.csv;([comment:"#"])] / lines that start with #The skipped lines take no part in the inference, the load or rejects. After skipRows, the comment lines that come before the header are skipped too, so the header is the first other line. A comment line is never ragged. The line numbers of rejects and of the errors count every line of the file, skipped or not, so they match an editor. With nrows, the lines are counted from the header, comment lines included, before the comment lines are left out.
skipRows and skipFooter cost nothing. comment reads the file once more to find the comment lines.
A line that doesn't have as many fields as the header, or as the first line without a header, is ragged. By default read loads it as 0: does, with nulls for the missing fields and without the extra fields, and gives no warning. The ragged option changes that:
q).csv.read[`:data.csv;([ragged:`skip])] / leave the ragged lines out
q).csv.read[`:data.csv;([ragged:`error])] / signal an error
'csv: 3 line(s) don't have 3 fields: line 3 has 2, line 4 has 4, line 6 has 1. Use rejects to list them, or set ragged to `skip.`skip and `error read the file once more to count the fields of every line. rejects lists the ragged lines whatever the option. A delimiter inside double quotes is not a field separator. As for 0:, a newline inside double quotes ends the line. A blank line is ragged, unless the file has one column. With nrows, the lines are counted before the ragged ones are left out.
.csv.infer[file]
.csv.infer[file; delimiter]
.csv.infer[file; options]Takes the same arguments as read and returns a table with one row per column of the file, showing the type read would use and the evidence for it.
| Column | Description |
|---|---|
column |
column name |
index |
position of the column in the file, from 0 |
qtype |
load type, as for 0:; " " means the column is skipped |
uncertain |
1b when the type is a guess worth checking, such as a date read from plain digits, or a type that frugal narrowed |
empty |
1b when every sampled value is empty |
fitsJ10, fitsJ12 |
1b when a symbol or string column could be encoded as a long with .Q.j10 or .Q.j12 |
ipAddress |
1b when the values look like IPv4 addresses (loaded as int) or IPv6 addresses (loaded as GUID) |
converted |
1b when read converts or post-processes the column after loading, so 0: with qtype doesn't load it the same way. See Loading a file in batches |
maxWidth |
maximum width of the sampled values |
maxDots |
maximum number of . in a value |
rules |
the rules that matched, in order |
granularity |
distinct values as a percentage of the sampled rows |
distinctCount |
number of distinct sampled values |
chars |
distinct characters in the sampled values |
q)select column,qtype,uncertain,maxWidth,granularity,distinctCount,rules from .csv.infer f
column qtype uncertain maxWidth granularity distinctCount rules
-------------------------------------------------------------------------
id J 0 2 100 40 40 100
price F 0 6 100 40 40 103
qty J 0 4 78 31 40 100
sym S 1 4 8 3 ,900
name * 0 7 100 40 40 50 901
date D 0 10 100 40 40 202
time T 0 12 100 40 40 302
ts P 1 29 100 40 40 401
flag B 0 1 5 2 40 100 501
active B 0 5 8 3 ,502
note * 0 15 100 40 40 50 901
uid G 0 36 100 40 20 602
empty C 0 0 0 0 ,30
ymd J 0 8 100 40 40 100To adjust the inferred types and load with them, pass them back as types:
q)ty:exec column!qtype from .csv.infer f
q)ty[`price]:"F"
q).csv.read[f;([types:ty])].csv.peek[file]
.csv.peek[file; delimiter]
.csv.peek[file; options]Takes the same arguments as read and returns the rows that infer samples, to look around in a file: the first rows, then blocks of rows from evenly spaced places in the rest of it. It uses the same sampling as infer, so it shows what the types are inferred from. The sample option sets the number of rows, and 0W returns every row. The columns, skipRows, skipFooter, comment, header, trimSpaces and delimiter options apply, and a pattern is sampled across its files, which must have the same columns, as for read. The nrows option has no effect, as it has none on the sample.
q).csv.peek[`:test/data/basic.csv;([sample:12;columns:`id`price`sym])]
id price sym
--------------
1 49.27 AAPL
2 61.7 MSFT
3 61.59 GOOG
4 50.66 AAPL
9 81.11 GOOG
13 18.38 AAPL
17 62.94 MSFT
21 57.07 GOOG
25 104.99 AAPL
29 94.81 MSFT
33 103.67 GOOG
37 25.67 AAPLThe values are symbols, as the rules see them, whatever the type of the column, and spaces around a value are dropped. The result has no line numbers. To see the first lines of a file as they are written, use read0 with a byte range, such as read0(`:data.csv;0;500).
.csv.rejects[file]
.csv.rejects[file; delimiter]
.csv.rejects[file; options]Takes the same arguments as read and returns the values that read would load as null although they hold text, and the lines that have a number of fields other than the header's. A value that does not fit the type inferred from the sample is the first kind, such as an abc in a column that the sampled rows made a float.
rejects checks the rows that read would load with the same options, and no others: the rows after nrows, and the lines that skipRows, skipFooter and comment skip, are not checked. To check a whole file, call it without those options.
| Column | Description |
|---|---|
column |
column name; null for a ragged line |
row |
position of the record among the data records of the file, from 0, counted before comment lines and ragged lines are left out. It indexes the table that read returns only when no line was left out; otherwise use line |
line |
line of the file, from 1, counting the header and every skipped line |
text |
the value as written, or the whole ragged line |
qtype |
the type that the value didn't parse as; " " for a ragged line |
q).csv.rejects[`:data.csv;([sample:3;frugal:1b])]
column row line text qtype
----------------------------------
id 4 6 "70000" H
price 3 5 "abc" E
when 3 5 "2024-13-45" D
7 9 "4,5"The lines come after the values. With ragged:`skip, the values of the ragged lines are left out, as read doesn't load them. See Lines with the wrong number of fields.
Empty values and the placeholders of the nulls option are not rejects, as they load as null. Symbol and string columns can't fail, so rejects doesn't check them. It loads the file, then reads again, as strings, the checked columns that loaded nulls, so on a clean file it costs little more than a read.
Char and boolean columns have no null of their own, so rejects checks the text of every value in them:
- Char columns hold one character. A longer value, such as
truein a column of single letters, loads as a blank char, and is a reject. An empty value is a blank char, not a reject. - Boolean columns hold
true/false,yes/no,1/0,t/fory/n, in any case. A column of single characters is read by q's own boolean parser, which takes only the single characters. Any other text loads as0b, and is a reject. Empty values andnullsplaceholders are rejects too, because q has no null boolean and loads them as0b, which says "false" where the value is unknown. To keep them as nulls, load the column as"S"or"*"withtypes, or as"H"for0/1.
Spaces around a value are not part of it, in char and boolean columns, as 0: drops them.
To fail a load that has such values, set strict: read then signals an error that counts the values per column, and rejects lists them. strict is about values: for ragged lines, set ragged.
q).csv.read[`:data.csv;([sample:3;frugal:1b;strict:1b])]
'csv: 3 value(s) did not parse as the type of their column: id 1, price 1, when 1. Use rejects to list them..csv.defaults holds the default options. The options of a submodule, such as the financial ones below, have their defaults in the submodule. An options dictionary passed to read, infer, peek or rejects overrides any of them; an unknown key signals an error.
The values are checked when the function is called, and a value outside its domain signals an error that names the option. A short or an int is read as a long.
| Option | Domain |
|---|---|
header, discardEmpty, frugal, trimSpaces, strict, convertDistinct, glob |
a boolean |
nrows |
a long, 0 or more, or null for all |
skipRows, skipFooter |
a long, 0 or more |
sample |
a long, 1 or more, or 0W for every row |
batchsize |
a long, 1 or more, or null for the whole file |
symMaxGranularity |
an integer from 0 to 100 |
columns |
a symbol or a list of symbols |
types |
a dictionary of column name to type char |
nulls |
a string or a list of strings |
decimal |
"." or "," |
dateOrder |
`mdy, `dmy or null |
ragged |
`fill, `skip or `error |
comment |
a string without a line ending |
fileColumn |
a symbol |
names |
a list of symbols, one for each column, or a dictionary of old name to new name |
rules |
a symbol or a list of symbols, each a known rule set |
| Option | Default | Description |
|---|---|---|
delimiter |
"" |
Field delimiter, a char atom. The default picks one from the file extension: tab for .tsv, | for .psv, otherwise comma. |
header |
1b |
Whether the first line holds the column names. |
rules |
`$() |
Rule sets added to the basic rules, which always run: `extended, `financial or both together (`extended`financial). See Type rules. |
types |
(`$())!"" |
Dictionary of column name to type char, overriding the inferred type. " " skips the column. Use the cleaned-up names that read returns. See Column types. |
columns |
`$() |
Load only these columns, in file order. Empty loads all. It decides which columns load: a column that it leaves out stays out, even if types or formats name it. |
nrows |
0N |
Number of rows to load. Null loads all. The load reads only the bytes holding those rows, but it doesn't limit inference, which samples the file as usual, or rejects and strict, which check the rows that load. |
skipRows |
0 |
Number of lines to skip at the start of the file, before the header. See Lines to skip. |
skipFooter |
0 |
Number of lines to skip at the end of the file, such as a total or a trailer record. |
comment |
"" |
Prefix of the lines to skip wherever they are, such as "#". A line is skipped when it starts with the prefix. "" skips none. |
batchsize |
0N |
Bytes of the file to load at a time; a batch ends at the next line end. Null loads the file at once. See Loading a file in batches. infer, peek and rejects ignore it. |
postProcess |
:: |
Applied to the loaded table, for example to drop rows or columns. Any value q can apply to a table works: a function, projection or composition. It isn't applied to an empty table. With batchsize it is applied to each batch, and read returns the results joined with raze, so it filters rows without holding the whole file in memory. See Loading a file in batches. infer, peek and rejects ignore it. |
sample |
5555 |
Number of rows to infer the types from: the first rows, and blocks of rows from nine evenly spaced places in the rest of the file. 0W uses every row of the file, and of every file that a pattern matches, which is slow for a large one; otherwise a pattern is sampled from up to ten of its files. nrows doesn't limit the sample. A file with a quoted value over several lines is sampled from its start only. |
frugal |
0b |
Narrow integers to int or short, and decimals to real, when the sampled values fit. Saves memory, but a larger value outside the sample loads as null. infer marks the narrowed types uncertain. |
symMaxGranularity |
10 |
Text columns load as symbols when the distinct values are less than this percentage of the sampled rows. Otherwise they load as strings. |
discardEmpty |
0b |
Skip columns with no values, instead of loading them as char. |
nulls |
("N/A";"#N/A";"NULL";"null";"NaN";"nan";"None";"-") |
Placeholders that are left out when inferring the type, so a numeric column that has them still loads as numbers, with a null for each. Text columns keep them. Add "NA" to extend it, or pass () to turn it off. |
decimal |
"." |
Decimal separator of numbers such as 1.234,56. "," makes . the thousands separator, so 1.234 is read as 1234. |
dateOrder |
` |
`mdy or `dmy to read dates written with the year last, such as 1/15/2024 or 15.01.2024, and the same followed by a time. Null leaves them to q's date format (\z), which is month first by default. |
merge |
(`$())!() |
Dictionary of a new column name to a date column and a time column, such as ([ts:`date`time]). The first is a date column and the second a time of day (T, U, V or N), both loaded: not left out by columns or skipped with a type of " ". The two become one timestamp column, at the position of the first source column. A null date gives a null timestamp. The new name can be that of one of the two source columns, which the new column replaces, but not of another column of the file: that signals an error, and so does a name that expand also adds. |
convertDistinct |
0b |
Convert IPv6 addresses, 12-hour times and the codes that expand splits once per distinct value, with .Q.fu. Much faster when values repeat, but needs more memory when they don't. See Performance. |
ragged |
`fill |
What to do with a line that has a number of fields other than the header's, `fill, `skip or `error. `fill loads the missing fields as nulls and drops the extra ones, as 0: does. `skip leaves the line out and `error signals an error. See Lines with the wrong number of fields. |
strict |
0b |
Signal an error when a value does not parse as the type of its column, instead of loading it as null. The error counts the values per column. See rejects. |
glob |
1b |
Whether the file name can be a pattern that matches several files, with the wildcards of like. 0b takes the path as it is. See Several files. |
fileColumn |
` |
Name of a symbol column to add, that holds the file each row comes from. Null adds none. See Several files. |
names |
`$() |
Names for the columns: a list that replaces the names of all of them, by position, or a dictionary of old name to new name that renames some. See Column names. |
trimSpaces |
0b |
Strip leading and trailing spaces from text columns, such as the padded I and ZOOZ W of NYSE Trade and Quote (NYSE TAQ) files. |
q).csv.defaults
delimiter | ""
header | 1b
rules | `symbol$()
types | (`symbol$())!""
columns | `symbol$()
nrows | 0N
skipRows | 0
skipFooter | 0
comment | ""
batchsize | 0N
postProcess | ::
sample | 5555
frugal | 0b
symMaxGranularity| 10
discardEmpty | 0b
decimal | "."
dateOrder | `
merge | (`symbol$())!()
nulls | ("N/A";"#N/A";"NULL";"null";"NaN";"nan";"None";"-")
convertDistinct | 0b
ragged | `fill
strict | 0b
glob | 1b
fileColumn | `
names | `symbol$()
trimSpaces | 0b
formats | (`symbol$())!()
expand | (`symbol$())!`symbol$()
refYear | 0N.csv.defaults is a copy: changing it does not change the module's defaults. To use your own defaults, keep them in a dictionary and pass it, for example .csv.read[file;myopts,([nrows:10])].
The types option takes the type characters of the c column of the datatypes table that 0: accepts, such as "J" for a long, "F" for a float, "D" for a date, "S" for a symbol and "C" for a char, and " " to skip the column. infer returns the characters that read would use.
To load a column as strings, use "*":
q).csv.read[`:test/data/basic.csv;([types:`id`name!"S*"])]Here id loads as symbols and name as strings. The override replaces the inferred type, so for a column with "*":
- No check decides between symbols and strings, so
symMaxGranularityhas no effect. The values load as the text of the file, one string for each, and are not turned into symbols, whatever the number of distinct values. - No conversion runs on it: an empty value is an empty string, not a null, a placeholder such as
N/Astays as text, and the text is not trimmed unlesstrimSpacesis set. - Its values can't fail to parse, so
rejectsandstricthave nothing to report for it.
Strings take more memory and time than symbols, so use "*" for text with many distinct values, such as free-text names, and "S" for codes that repeat. A type that doesn't fit the values, such as "J" for text, loads them as nulls, which rejects lists.
read finds most dates and times by itself, including dateOrder for the year last. For a format that it doesn't know, such as 15-Jan-2024, 20240115 093000 or 9.30 for 9:30, give the format of the column with the formats option. The format is modeled on C's strptime, with this subset of its codes:
| Code | Reads |
|---|---|
%Y |
4-digit year |
%y |
2-digit year: 70 to 99 are 19yy, 00 to 69 are 20yy |
%m |
month, 1 or 2 digits |
%d |
day, 1 or 2 digits |
%b |
month abbreviation, such as Jan, in any case |
%B |
month name, such as January: any letters, read by their first three |
%H |
hour, 0 to 23 |
%I with %p |
hour 1 to 12, with AM or PM in any case |
%M, %S |
minute and second |
%f |
fraction of the second: 1 to 9 digits, as in .5 or .123456 |
%% |
a percent sign |
Any other character must be in the value as it is. A format needs a year and a month for a date, and an hour for a time: %Y-%m is the first of the month, and %M:%S is an error. The type follows the format:
| The format has | Type |
|---|---|
| a date | D |
| a date and a time | P |
| a time of day | T, or N (timespan) with %f |
q).csv.read[`:data.csv;([formats:`day`at`when!("%d/%m/%Y";"%H.%M.%S.%f";"%d-%b-%Y %I:%M %p")])]A value that doesn't fit its format, or has an impossible date such as 31/04/2024 or an hour of 25, loads as null, and rejects lists it. An empty value, and a placeholder of nulls, are null without being rejects. With strict, a value that doesn't fit signals an error.
infer gives the type of such a column with converted set to 1b and rule 2. As a column in formats is read by its format only, the types option can't name it too.
When all the values of a column are as wide as the format can make them, as with %Y/%m/%d %H:%M:%S.%f over fixed-width values, read converts the column with vector operations, which is typically a small cost next to loading it. Values of mixed width, such as 1/5/2024 among 15/01/2024, or %B, are converted one by one, which takes much longer for a large file. Zero-pad the values if you can, and use a pattern such as %d/%m/%Y only for the dates that need it.
The defaults of these options are in csv/temporal.q, and .csv.defaults includes them.
| Option | Default | Description |
|---|---|---|
formats |
(`$())!() |
Dictionary of column name to the format of its dates or times, such as ([formats:`day`at!("%d-%b-%Y";"%H.%M")]). See Date and time formats. |
The defaults of these options are in csv/financial.q, and .csv.defaults includes them.
| Option | Default | Description |
|---|---|---|
expand |
(`$())!`$() |
Dictionary of column name to `occ or `futures. Adds columns that decode that column, placed after it: Root, Expiry, PutCall and Strike for an OCC option symbol such as AAPL 240119C00150000; Root and Expiry (a month) for a futures code such as ESZ4 or ESH25. Columns are named after the source, for example optRoot. Codes that don't parse, or an OCC symbol with a date that is not in the calendar, give nulls. The source column must be loaded, not left out by columns or skipped with a type of " ", and it must hold text: a column that is inferred as a number needs types of "S" or "*". expand doesn't need rules:`financial, which only affects how identifiers are inferred. A column of the file with one of these names signals an error, as it would be replaced. |
refYear |
0N |
The first year that a futures code with a 1-digit year can mean, so with 2024, ESZ4 is December 2024 and ESZ3 is December 2033. Null is the current year. A 2-digit year is always 20yy. |
The rules run in turn on the sampled values of each column. A rule only applies to columns still at the type an earlier rule left, so the order matters. The rules column of infer lists the rules that matched, in the order they ran.
A rule number says what the rule reads and which set it belongs to. The hundreds digit is the kind of value, in the table below. The last two digits are the family of the set: 00 to 59 are the basic rules, 60 to 79 are the extended rules, and 80 to 99 are for rule sets that you add by name. The financial set uses the endings 80 to 85 (rules 180 and 680 to 685), so 86 to 99 are free for your own sets.
| Numbers | Kind |
|---|---|
| 1 to 99 | steps that are not a type: the types and columns options, long values, empty columns, and the move from maybe numeric to text |
| 100s | numbers |
| 200s | months and dates |
| 300s | times |
| 400s | timestamps and timespans |
| 500s | chars, booleans and bytes |
| 600s | addresses and identifiers |
| 900s | the fallback to symbols and strings |
The basic rules always run. They read a value as a date or time only when it is written like one: 2024-01-15, 2024.01.15, 09:30:00, 2024-01-15T09:30:00.123. The `extended rules also try plain digits: 20240115 as a date, 235959 as a second, 2359 as a minute, a 9-digit number as a time and a 15-digit number as a timespan (as in NYSE TAQ files). Those guesses are often wrong for ordinary integer columns, so they are off by default; infer flags them with uncertain.
The `financial rules read bond prices in 32nds and the instrument identifiers ISIN, CUSIP, OCC option symbols, SEDOL, FIGI and LEI. Each identifier is checked against its check digit, so a column only matches when every sampled value is valid. Use `extended`financial for both sets.
q)select column,qtype,uncertain,rules from .csv.infer[f;([rules:`extended])] where column in `price`ymd
column qtype uncertain rules
-----------------------------------
price F 0 40 103
ymd D 1 40 100 261These rules always run.
| Rule | Type | Matches |
|---|---|---|
| 1 | any | type set by the types option |
| 2 | D, P, T or N |
type set by the formats option, which reads the column as text and converts it by its format |
| 10 | skip | column not in columns |
| 20 | * |
values longer than 30 characters |
| 30 | C or skip |
no values (skip when discardEmpty) |
| 40 | contains a digit, so maybe numeric | |
| 50 | maybe numeric, but no number, date or time rule matched, so back to undecided text | |
| 100 | J |
integers |
| 101, 102 | I, H |
with frugal, integers narrowed to the smallest type that holds the sampled values |
| 103 | F |
decimals |
| 104 | E |
with frugal, decimals narrower than 9 characters |
| 105 | J |
integer with thousands separators, a currency symbol, a percent sign or parentheses: 1,234,567, $5, 12%, (7). See the forms |
| 106 | F |
the same with decimals: $1,234.50, 1.25%, (1,234.50) |
| 107 | F |
fraction such as 1 3/4 |
| 200 | M |
month such as 2024-01 |
| 201 | D |
date with the year last such as 1/15/2024 or 15.01.2024, read in the dateOrder |
| 202, 203 | D |
date with -, / or . separators |
| 204 | D |
date such as 15jan2024 |
| 300 | T |
12-hour time such as 9:30:00 AM or 01:15 pm |
| 301 | U |
hh:mm |
| 302, 303 | T, V |
hh:mm:ss, with or without milliseconds |
| 400 | P |
ISO 8601 timestamp that ends in Z or a UTC offset such as +05:30 or -0500, loaded as UTC. The offset has minutes 00 to 59 and is at most 14:00 either way |
| 401 | P |
date followed by a time |
| 402 | P |
date with the year last followed by a time, such as 1/15/2024 9:30:00 AM, read in the dateOrder |
| 403 | N |
timespan such as 0D09:30:00 |
| 500 | C |
single character |
| 501 | B |
0/1, t/f, y/n, with both a true and a false value |
| 502 | B |
true/false, yes/no, in any case |
| 503 | X |
two hex digits |
| 600 | I |
IPv4 address |
| 601 | G |
IPv6 address such as 2001:db8::1, loaded as a GUID. Hex groups, with one :: at most, and the last 32 bits can be an IPv4 address: ::ffff:192.0.2.128. Zones (%eth0), prefix lengths (/64) and brackets are not accepted |
| 602, 603 | G |
GUID, optionally in braces |
| 900 | S |
granularity under symMaxGranularity |
| 901 | * |
anything else |
These rules run when rules includes `extended. They guess a type from plain digits.
| Rule | Type | Matches |
|---|---|---|
| 260 | M |
month such as 202401 |
| 261 | D |
6 or 8 digits such as 20240115 |
| 360 | V |
6 digits such as 235959 |
| 361 | U |
4 digits such as 2359 |
| 362 | T |
decimal such as 093000.123 |
| 363 | T |
9 digits |
| 460 | P |
Unix epoch of 10, 13, 16 or 19 digits (seconds, milliseconds, microseconds, nanoseconds) between 2000 and 2100 |
| 461 | N |
anything else that parses as a timespan |
| 462 | N |
15 digits |
| 560 | B |
only one of 0, 1, t, f, y, n, such as a column of 0 |
These rules run when rules includes `financial.
| Rule | Type | Matches |
|---|---|---|
| 180 | F |
bond price in 32nds such as 99-16, 99-16+ or 99-162, as a decimal price |
| 680 | S |
ISIN such as US0378331005, with a valid check digit, whatever the number of distinct values |
| 681 | S |
CUSIP such as 037833100, with a valid check digit, whatever the number of distinct values |
| 682 | S |
OCC option symbol such as AAPL 240119C00150000: a root of 1 to 6 capitals, digits or points, padded with spaces, an expiry date in the calendar, C or P, and the strike. expand splits the same symbols |
| 683 | S |
SEDOL such as 0263494, with a valid check digit |
| 684 | S |
FIGI such as BBG000BLNNH6, with a valid check digit |
| 685 | S |
LEI such as HWUPKR0MPOU8FGXBT394, with valid check digits |
Notes on the formats in these tables:
- Rules 105 and 106 accept these forms of a number
9, which is digits with thousands separators and a decimal point:9,+9,-9,9-, a currency symbol ($,€or£) before the number or between the sign and the number,$-9and-$9,9%, and any of these without the sign in parentheses, as($9). A currency symbol and a percent sign occur at most once, in those places only, and parentheses enclose the whole number. Spaces are allowed before and after the number only. Anything else, as1$2,12),1 2,$$5,5%-,(-5)or$(5), is not a number: a column that has such a value in the sample is not inferred as numeric, and one that has it outside the sample loads it as null, whichrejectslists. - Rules 105 and 106 read a percent as written:
1.25%loads as1.25, not0.0125. Parentheses and a trailing-make a negative number. Thousands separators must be in groups of three, so a European1.234,56is not read. - Rule 400 converts the offset, so
2024-01-15T09:30:00+05:30loads as2024.01.15D04:00:00. An offset that isn't valid, such as+24:00,+05:60or+99:99, makes the value null, and the column is not inferred as a zone-aware timestamp. A timestamp without a zone is left to rule 401. - Rule 180 reads the last digit as eighths of a 32nd and
+as a half, so99-162is99 + 16.25/32. It isuncertain, as a value such as10-12could be something else. - With
decimalset to",", a value with only a.or only a,, such as1.234or12,5, is read as a formatted number. A column of plain1.5values is then not read as decimals, so set it only for files that use the comma. - Rules 680 to 685 need a letter among the sampled values. A column of all-digit CUSIPs or SEDOLs loads as integers, which drops leading zeros. Pass
typesto load it as symbols.
read takes delimited text, one record to a line, as 0: does, and adds the type inference and the conversions around it.
- Delimiter. One character, from the
delimiteroption or the file name: tab for.tsv,|for.psv, comma otherwise. - Quotes. A field in double quotes can contain the delimiter, and the quotes are not part of the value. Inside quotes, a doubled quote is one quote:
"he said ""hi"""loads ashe said "hi". - A record is a line. A newline inside quotes still ends the record, so a quoted field that spans several lines is not supported: its first line is one record, and the rest are others, which have the wrong number of fields.
readfills or skips them, or signals an error, asraggedsays, andrejectslists them. Inference then reads the file from its start only, as a sample from the middle of the file could begin inside a quoted field. To load such a file, convert it first. - Line endings.
\nor\r\n. - Encoding. The file is read as bytes, with no conversion. UTF-8 text loads as it is in symbol and string columns, and a column of single characters needs single-byte characters. A UTF-8 byte order mark at the start of the file is skipped. UTF-16, Latin-1 and other encodings are not converted, so convert them to UTF-8 first. In a header, only ASCII letters, digits and
_are kept: see column names.
A rule set keeps the rules of one domain apart from the others, so adding a domain does not change how existing files load. A set is a submodule next to csv/init.q that exports one dictionary, extension, with everything the set adds, and one line in csv/init.q that registers it. The financial set, in csv/financial.q, is the model to copy.
-
Write a function per phase. The phases run in this order, and the functions of a phase run after the basic rules of that phase:
Phase Runs after Sees columns that are still `numberthe number rules, including the addresses, GUIDs and dates with separators "n", maybe numeric`timethe time, timestamp and timespan rules "n", maybe numeric`textthe char, boolean and byte rules "?", undecided textA function takes the
schematable and the options, and returns the schema. Each rule is anupdatethat sets the type anduncertain, and appends its number torules. The conditions test the evidence inschema:dvals(the distinct sampled values, as strings),chars,maxWidth,maxDotsandgranularity. -
Choose unused rule numbers. Pick endings from 86 to 99 for your set, as
financialhas 80 to 85, and don't use an ending that another set has. Give each rule the hundreds digit of its kind and one of your endings: the example below is in the 600s, for addresses and identifiers, and has the ending 90, so its rule is 690. -
Describe the set in
extension. Every key is optional. Withoutnamethere is no rule set, and the phases don't run:Key Value namethe name of the set, for the rulesoptionphasesdictionary of phase to its function convertersdictionary of rule number to a function of the options and the strings, for a rule whose values 0:can't load, such as rule 180 offinancial(bond prices). A column whose last rule has a converter loads as strings, and the converter converts it.defaultsthe options of the set and their defaults, which join defaultschecka function of the options that signals an error for a value of the set's options that can't work, and returns the options posta function of the options and the loaded table that returns the table, to add columns after loading, as expanddoes. It runs whether or not the set is inrules, as an option turns it on.reads,addsfunctions of the options that return a dictionary of option to the columns of the file that postreads and to the columns that it adds, so thatreadchecks the names and loads the columns thatpostreads as0:can'tThe converters, options and set name must not be registered already, and the phases must be
number,timeortext, with a function each, orregistersignals an error. -
Register the set. Add
register(use`.yourset)`extensiontocsv/init.q, after the others. Therulesoption accepts the set name from then on, and an unknown name signals an error that lists the available sets. -
Keep the set in its submodule. The functions that recognise a format, the ones that convert it, and the rules that use them are in the submodule, so it can be tested on its own and moved to a module of its own later.
csv/util.qhas the helpers that the submodules share, such asheadFirst. Check the type of the parameters of the functions, withstr:`Cfor a string andstrings:`(the null symbol) for a list of strings, and document the exported functions with qdoc. Thetemporalsubmodule registers an extension with noname, only for thedefaultsandcheckof itsformatsoption. Its formats are used by the basic rules, which keep their converters incsv/init.q. -
Document and test. Add the rules to the tables above, and add a data file and tests to
test.q. The tests of the functions in a submodule go in a file of their own, such astest/financial.q, thattest.qloads, so they move with the submodule.
This set reads currency pairs such as EUR/USD as symbols, whatever their number of distinct values:
fxTextRules:{[schema:table;opts:dict]
pair:{all x like"[A-Z][A-Z][A-Z]/[A-Z][A-Z][A-Z]"};
update qtype:"S",(rules:rules,'690),uncertain:0b from schema
where qtype="?",maxWidth=7,pair peach dvals}
extension:([name:`fx;phases:enlist[`text]!enlist fxTextRules])
export:([extension])and in csv/init.q:
register(use`.fx)`extensionRule sets are independent, so .csv.read[file;([rules:`fx`financial])] runs both.
The submodules are util (shared helpers), network, numeric, temporal and financial. They are internal to the module: the public interface is the functions in Functions, and the submodules can change or move.
read costs about as much as 0: with the same types. The rules run on the sample only, and 0: then reads the whole file once, with the secondary threads of the process (-s) in the same way, so the load speeds up with them as 0: does. Setting nrows adds a pass over the bytes of those rows to find where they end, which is small next to the parse, but it doesn't speed up with threads. To load a file in pieces, see Loading a file in batches.
These add to the cost:
- Longs and floats. Integers load as longs and decimals as floats, which take more memory than shorts, ints and reals. Set
frugalto save memory and some load time, at the risk of nulls. - Formats that
0:can't read. A column of a type rule with a converter, such as rule 105 ($1,234) or rule 201 (1/15/2024), loads as strings and then converts. The conversion uses vector operations, and dates and bond prices convert once per distinct value, as they repeat. - IPv6 addresses, 12-hour times and
expand. These convert one value at a time, and so do date-times with a 12-hour time such as1/15/2024 9:30:00 AM, which makes them the slowest formats to load. When the values repeat, setconvertDistinctto convert each distinct value once with.Q.fu, which is much faster. When the values are all different, it needs more memory and gains nothing, so it is off by default. - Text that loads as strings. A text column loads as symbols only when few of its sampled values are distinct (
symMaxGranularity). Strings take more memory and time than symbols. Passtypessuch as([types:([Symbol:"S"])])to load a column as symbols. rejectsandstrict. They load the file, then read again as strings the columns that loaded nulls, and as symbols the char and boolean columns, which they check by their distinct values.raggedandcomment.`skipand`error, and acommentprefix, read the bytes of the file once more to count the fields of each line and find the comment lines, in one pass for both.rejectsalways does. The count uses vector operations, so it is typically marginal next to the load.
The time of inference does not grow with the size of the file, as it reads only the first rows and nine blocks of rows, so it is typically marginal next to the load. Sampling from several places matters for sorted files. NYSE TAQ files are sorted by symbol, so their first rows are all of one ticker: a sample from the start alone would make Symbol a char column and cut every later ticker to its first letter.
The sample can still miss values. In NYSE TAQ quotes, Short_Sale_Restriction_Indicator can hold only 0 in every sampled block and letters further down, so it loads as long and the letters load as null. Check the types with infer, find such columns with rejects, and fix them with types, here ([types:([Short_Sale_Restriction_Indicator:"C"])]).
read loads the whole file into memory. With the batchsize option it loads the file a batch of lines at a time, and applies the postProcess function to each batch. Use it to filter rows, save each batch to a database or publish it to a tickerplant, for a file that is too large to load at once.
q).csv.read[`:trades.psv;([batchsize:100000000;postProcess:{select from x where size>10000}])] / only the large trades, from batches of about 100 MB
q).csv.read[`:trades.psv;([batchsize:100000000;postProcess:{`trades upsert x;()}])] / save every batch, and return nothingpostProcess is applied to a table and can return anything: it can be any function, projection or composition. The default, ::, is the identity: it returns the table. read returns the results on the batches joined with raze, so a function that returns a filtered or aggregated table gives one table, and one that returns () leaves nothing in memory. Only the rows that postProcess keeps are in memory, and a batch is dropped once processed. Without batchsize, postProcess is applied to the whole table.
read infers the types once, from the sample, then loads the batches with them. The function gets a table with the columns and the conversions that read gives the whole file: booleans, formatted numbers, time zones, epochs, trimSpaces, merge, expand, and the other options all work the same in a batch. It is never applied to an empty table, so it isn't called for a batch with no rows left, for example one of comment lines, and a file with no rows returns its empty table, with or without batchsize.
A batch has the bytes of whole lines, so batchsize is a size to reach, not an exact one. The header is in the first batch only.
With the default postProcess, read joins the batches and returns the table, as it does without batchsize. The result is the same, and the memory for the text of the converted columns is that of a batch, not of the file. A smaller batch costs a little more time, since each one has a fixed cost: use batches of tens or hundreds of megabytes.
Some behaviours depend on the batch:
ragged:`erroris checked before the first batch loads, sopostProcessis not called for a file with a ragged line. Withstrict, a batch with a value that doesn't parse signals an error, afterpostProcesshas been called on the batches before it.convertDistinctapplies.Q.futo each batch, so it converts the distinct values of a batch, not of the file.- Symbols are not enumerated. If
postProcesswrites to a database, enumerate them there, for example with.Q.en.
As the types come from a sample, check them as for read: increase sample, and call rejects on the file.
If every column loads with its qtype, .Q.fsn with 0: and the types from infer does the same job, with no batchsize. The converted column of infer is 1b for the columns that 0: can't load from a type char: booleans written as true/false or yes/no, formatted numbers such as $1,234.50, ISO 8601 timestamps with a time zone, Unix epochs, bond prices, 12-hour times, and dates written with the year last, and the text columns with trimSpaces, and the columns that merge and expand use. A file with such a column loaded with .Q.fsn and its qtype gives nulls or wrong values, and no error. Use batchsize for it.
q)f:`:trades.psv
q)i:.csv.infer f
q)if[any i`converted;'"csv: these columns need read: ",", "sv string exec column from i where converted]
q)ty:exec qtype from i
q)names:exec column from i where not qtype=" "
q)atStart:1b / the first chunk starts with the header
q)onChunk:{if[atStart;x:1_x;atStart::0b];`trades upsert flip names!(ty;"|")0:x}
q).Q.fsn[onChunk;f;100000000] / chunks of up to 100 MBUse the delimiter of the file in place of "|". This recipe reads every line of the file, so with skipRows, skipFooter or comment, leave those lines out in onChunk too, or use batchsize.
read returns a table, and with batchsize and postProcess it hands each batch to a function, so a file of any size can go to a database or to a feed. The recipes below load a file of NYSE TAQ trades. They use rules:extended, which reads the Timecolumn as a timespan, andtypesto loadSymbol` as symbols, as the types that a database or a tickerplant expects must be right before the first batch is sent:
q)f:`:test/data/EQY_US_ALL_TRADE_20260401.psv
q)o:([rules:`extended;types:([Symbol:"S"]);columns:`Time`Exchange`Symbol`TradeVolume`TradePrice])save is a q keyword, so don't name a function save.
For a file that fits in memory, load it and write it with .Q.dpft, which enumerates the symbols, sorts the table and applies the p# attribute to the partitioning column. The table must be a global variable named like the table to write, and date becomes a column of the saved table:
q)db:`:/data/hdb
q)trade:.csv.read[f;o]
q).Q.dpft[db;2026.04.01;`Symbol;`trade]
`tradeA file has no date of its own, so give the partition. To write one file per day, call it once for each file with that file's date. The result is a database that you load with \l /data/hdb.
Write each batch to the partition as it arrives. .Q.en enumerates the symbols of a batch against the sym file of the database, and upsert to the path of a splayed table appends the rows. Return () so that nothing builds up in memory. When the last batch is written, sort the partition by symbol and apply p#, as .Q.dpft does:
q)db:`:/data/hdb
q)part:` sv db,`2026.04.01`trade
q)toDisk:{[x](` sv part,`)upsert .Q.en[db;x];()}
q).csv.read[f;o,([batchsize:100000000;postProcess:toDisk])]
()
q)`Symbol xasc part
q)@[part;`Symbol;`p#]The database then has date, Symbol, Time, Exchange, TradeVolume and TradePrice, with Symbol parted. The batchsize is in bytes of the file, so choose it for the memory that one batch takes.
Send each batch to a tickerplant with its update function .u.upd takes the table name and the rows. The send is asynchronous, so the rows go out as fast as they load, and neg[h](::) flushes the connection:
q)h:hopen 5010
q)publish:{[x]neg[h](`.u.upd;`trade;x);neg[h](::);()}
q).csv.read[f;o,([batchsize:1000000;postProcess:publish])]
()
q)hclose hThe tickerplant checks the table and the columns against its schema, so give read the same column names, order and types as the schema: use columns to pick and order the columns, types and formats to set the types, and names to rename. A tickerplant time column is usually a timespan and the date is added by the tickerplant. To publish to a plain q process, give insert in place of .u.upd.
A KX Database Service takes the rows through a Reliable Transport (RT) publisher, and the tables must be created in the service before the first batch is sent, for example with the DB Service client module. Then publish each batch through the RT publisher, which takes the same call as a tickerplant:
$ q startq.q
q)rtPub:.rt.pub ([path:"/tmp/rtpub";stream:"data";cluster:enlist":localhost:5002";publisher_id:"csv"])
q)publish:{[x]rtPub(`.u.upd;`trade;x);()}
q).csv.read[f;o,([batchsize:1000000;postProcess:publish])]These recipes publish each batch as soon as it is parsed: they replay a file as fast as it loads, with no relation to the times in it. They are for loading history into a feed or a database, not for a live feed.
To replay a file at the pace of its own times, make postProcess wait for the time of each batch before it publishes. This works with the functions that csv has, because a postProcess function can take as long as it likes. The batch is sent when the clock has advanced as far as the batch's last row has from the first, divided by speed:
q)os:use`kx.os
q)h:hopen 5010
q)speed:1 / 1 is the pace of the data, 20 is twenty times faster
q)start:.z.p
q)t0:0Nn
q)replay:{[x]
if[null t0;t0::first x`Time];
due:start+"n"$(last[x`Time]-t0)%speed;
if[0<wait:due-.z.p;os.sleep wait];
neg[h](`.u.upd;`trade;x);neg[h](::);()}
q).csv.read[f;o,([batchsize:100000;postProcess:replay])]A batch is sent when its last row is due, so a larger batchsize publishes in bigger and less frequent steps. A batch that is late, because parsing or the connection is slow, is sent at once, and the later batches stay on the same schedule. The wait is the sleep of the OS module, which recent KDB-X installers install by default.
Publishing at the pace of the data is for demos and for trying out a feed, and this recipe is not designed for stress tests: one process parses, waits and sends one batch at a time, so it can't produce a high or steady rate.
What csv can't do is publish a file that is still being written, such as a log that grows. read loads the file as it is when the call starts and has no way to start from a byte or to report where it stopped, so a second call would load the first part again. A live feed from a growing file would need that, for example a start option and the byte where the last batch ended, to call read again for the new lines. It is not part of the module today.
The csv module is based on csvutil.q, the well-known CSV utility, and is similar to it: both infer the type of each column from a sample of rows, with the same basic and extended rules. csvutil.q is deprecated and no longer supported, so for KDB-X it is highly recommended to migrate scripts that use it to this module. The table maps its functions to the module's.
csvutil.q loaded with its extended rules by default, and narrowed integers and decimals to the smallest type that held the sampled values. The options of the mappings, rules:`extended and frugal:1b, give the same rules and the same narrowing. The types are then those of csvutil.q for the same rows, apart from the differences listed after the table. On the file test/data/basic.csv that is one column: active, which holds true and false, is a boolean here and symbols there.
| csvutil.q | csv module |
|---|---|
.csv.read[file] |
.csv.read[file;([rules:`extended;frugal:1b])] |
.csv.basicread[file] |
.csv.read[file;([frugal:1b])] |
.csv.read10[file] |
.csv.read[file;([rules:`extended;frugal:1b;nrows:10])] |
.csv.basicread10[file] |
.csv.read[file;([frugal:1b;nrows:10])] |
.csv.info[file] |
.csv.infer[file;([rules:`extended;frugal:1b])] |
.csv.basicinfo[file] |
.csv.infer[file;([frugal:1b])] |
.csv.infoonly[file;cols] |
.csv.infer[file;([rules:`extended;frugal:1b;columns:cols])] |
.csv.infolike[file;pattern] |
.csv.infer[file;([rules:`extended;frugal:1b;columns:c where lower[c:cols .csv.peek[file;([sample:1])]]like lower pattern])] |
.csv.data[file;info] |
.csv.read[file;([types:exec column!qtype from info])], where info is the table from infer |
.csv.colhdrs[file] |
cols .csv.peek[file;([sample:1])] |
.csv.DELIM, .csv.READLINES, ... |
the delimiter, sample, ... options |
.csv.ZAPHDRS |
(`$lower each(string cols t)except\:"_")xcol t on the table t that read returns. The names that read gives keep their case and underscores, so use those in types and columns |
POSTLOADEACH, POSTLOADALL |
read ran them one after the other on the table, so postProcess:{postloadall postloadeach x} is the same. With batchsize, postProcess is applied to each batch, as POSTLOADEACH was to a chunk, and you apply the other function to the table that read returns |
bulkload[file;info] |
.csv.read[file;([batchsize:n;postProcess:f])], which returns the table instead of inserting into DATA; see Loading a file in batches |
There is no option for a function on the whole table after the batches: read returns a table, and applying a function to it is one call.
The differences:
readuses only the basic rules by default. The`extendedrules, which werecsvutil.q's default, are opt-in.- Integers load as longs and decimals as floats unless
frugal:1bis set, whichcsvutil.qalways did: it narrowed them to the smallest type that held the sampled values. The mappings above set it, andrules:`extendedfor the functions that used the extended rules. - The sample comes from the start and nine evenly spaced places in the file, not only from the first
READLINESrows. - The type inference that
csvutil.qcalledinfois nowinfer. The module has no per-column statistics:describeof thetblmodule returns them for any table, such as the onereadreturns. - There is no
SYMMAXWIDTHlimit: whether text loads as symbols depends only on how often values repeat (symMaxGranularity). Values longer than 30 characters always load as strings, so long text never becomes a symbol. There is noFORCECHARWIDTHoption for this limit. - The columns of
inferhave descriptive names.csvutil.q'sc,ci,t,maybe,empty,j10,j12,ipa,mw,mdot,rules,gr,ndvanddcharare nowcolumn,index,qtype,uncertain,empty,fitsJ10,fitsJ12,ipAddress,maxWidth,maxDots,rules,granularity,distinctCountandchars. Soexec c!t from infobecomesexec column!qtype from .csv.infer file. inferhas norescolumn..Q.idalready renames columns that clash with q keywords.true/falseandyes/nocolumns load as booleans (rule 502).csvutil.qloaded them as symbols.- Without the
`extendedrules, a column holding a single one of0,1,t,f,yornno longer loads as boolean (rule 560 is now extended-only). A column of0and empty values, such as an I/O counter, stays numeric and keeps its nulls; as a boolean the nulls became0b. - Headers and, without a header, column counts respect double quotes, so a quoted name can contain the delimiter.
- The header can be any width;
csvutil.qread at most 25000 characters of it.
