如文档所述,CSV阅读器不会执行自动数据转换。您具有QUOTE_NONNUMERIC格式选项,但这只会将所有未引用的字段转换为浮点数。这与其他csv阅读器非常相似。
我不认为Python的csv模块对这种情况完全没有帮助。正如其他人已经指出的那样,这
literal_eval()是一个更好的选择。
以下内容可以工作并进行转换:
- 弦
- 整型
- 漂浮
- 清单
- 词典
您也可以将其用于boolean和NoneType,尽管它们必须相应地进行格式化
literal_eval()才能通过。LibreOffice
Calc在Python中将布尔值大写时,以大写字母显示布尔值。另外,您还必须将空字符串替换为
None(不带引号)
我正在为mongodb写一个可以完成所有这些工作的导入器。以下是我到目前为止编写的代码的一部分。
[注意:我的csv使用制表符作为字段定界符。您可能也想添加一些异常处理]
def getFieldnames(csvFile): """ Read the first row and store values in a tuple """ with open(csvFile) as csvfile: firstRow = csvfile.readlines(1) fieldnames = tuple(firstRow[0].strip('n').split("t")) return fieldnamesdef writeCursor(csvFile, fieldnames): """ Convert csv rows into an array of dictionaries All data types are automatically checked and converted """ cursor = [] # Placeholder for the dictionaries/documents with open(csvFile) as csvFile: for row in islice(csvFile, 1, None): values = list(row.strip('n').split("t")) for i, value in enumerate(values): nValue = ast.literal_eval(value) values[i] = nValue cursor.append(dict(zip(fieldnames, values))) return cursor


