如果你使用 CSV,你会得到字符串。请参阅文档:http ://docs.python.org/2/library/csv.html#module-contents
“不执行自动数据类型转换。”
@hcwhsa 为您指出了一个答案,该答案显示了如何使用ast.literal_eval()
来猜测类型。这不是太难:
import ast
import csv
def convert_type(s):
try:
return ast.literal_eval(s)
except (ValueError, SyntaxError):
return s
def convert_csv_row(lst):
return [convert_type(x) for x in lst]
data = csv.reader(open('pppp.csv','r', newline=''))
converted = [convert_csv_row(row) for row in data]
print(converted)
但实际上,如果您想保留类型,为什么还要使用 CSV?除非您将数据导出到电子表格或其他东西,否则我建议您使用 JSON 格式。
import json
list_of_ee = [["a","m",15],["w","p",34]]
with open("test.json", "wt") as f:
f.write(json.dumps(list_of_ee))
with open("test.json", "rt") as f:
s = f.read()
lst = json.loads(s)
print(lst)
assert list_of_ee == lst
JSON 是将数据导出到其他程序的好方法。
但如果你只是想为自己的 Python 程序保存数据,那就更简单了:只需使用pickle
. http://docs.python.org/2/library/pickle.html
import pickle
list_of_ee = [["a","m",15],["w","p",34]]
with open("test.pickle", "wb") as f:
f.write(pickle.dumps(list_of_ee))
with open("test.pickle", "rb") as f:
bytes_data = f.read()
lst = pickle.loads(bytes_data)
print(lst)
assert list_of_ee == lst
您需要以pickle
二进制模式写入和读取文件,而不是文本模式。您还pickle
可以保存几乎任何 Python 原生类型,而不仅仅是 JSON 支持的基本类型。但几乎只有 Python 程序读取pickle
文件。