如何将KDB查询结果写入文本文件?遇类型不匹配错误求助
KDB写入表到文件报错“type: Mismatched types errors”的解决方法
错误原因
neg[fileHandle] 仅支持写入原始字节或字符串类型数据,直接传入KDB表(复合类型)会触发类型不匹配错误。
解决方案
方法1:手动转换表为字符串并通过句柄追加写入
通过string函数将表转换为可写入的字符串格式,同时打开文件时指定追加模式(hopen第二个参数传1):
filePath:hsym `$("/c/d/f/a.txt"); // 以追加模式打开文件 .co.fileHandle: hopen[filePath;1]; // 执行查询 x:select a,c from tab; // 将表转为带换行的字符串(包含表头) tabContent: string[cols x], "\n", raze string[each x], "\n"; // 写入文件 neg[.co.fileHandle] tabContent; // 操作完成后关闭句柄 hclose .co.fileHandle;
如果需要避免重复写入表头,可先判断文件是否存在,首次写入时包含表头,后续仅写入数据行:
filePath:hsym `$("/c/d/f/a.txt"); .co.fileHandle: hopen[filePath;1]; x:select a,c from tab; if[not filePath in key `.:; // 文件不存在时写入表头 neg[.co.fileHandle] (string[cols x], "\n"); ]; // 写入数据行 neg[.co.fileHandle] (raze string[each x], "\n"); hclose .co.fileHandle;
方法2:使用0:命令直接追加(更简洁)
不需要手动管理文件句柄,利用0:的追加模式(第二个参数传1)实现写入:
// 首次写入(包含表头,覆盖原有文件) 0: `/c/d/f/a.txt 0: select a,c from tab; // 后续追加查询结果(仅写入数据行,跳过表头) 0: `/c/d/f/a.txt 1: 1_ string select a,c from tab2;
其中1_ string ...用于移除表头行,避免重复写入表头。
内容的提问来源于stack exchange,提问作者Code Enthusiast
相关产品推荐
相关产品推荐

