[英]Python: My csv.reader imports csv file as text
After importing CSV
file, the output appears like [['1', '2', '3']]
. 导入
CSV
文件后,输出显示为[['1', '2', '3']]
。 How can I make sure it is imported as a number? 如何确保将其作为数字导入?
With the csv module reader
function a row read from the csv file is returned as a list of strings. 使用csv模块
reader
功能,将从csv文件读取的行作为字符串列表返回。 If you want unquoted numbers not to be returned as strings use the quoting=csv.QUOTE_NONNUMERIC
option. 如果您不希望将未加引号的数字不作为字符串返回,请使用
quoting=csv.QUOTE_NONNUMERIC
选项。 However, be aware that this option will convert to float. 但是,请注意,此选项将转换为float。 If you want to process or display these numbers as
int
s then you will have to cast them as int
. 如果要处理或将这些数字显示为
int
则必须将其强制转换为int
。
This is your csv file: 这是您的csv文件:
1,2,3
4,5,6
7,8,9
Assuming you want a list of lists output: 假设您想要列表输出列表:
import csv
tst = open('test.csv')
l = []
reader = csv.reader(tst, quoting=csv.QUOTE_NONNUMERIC)
for line in reader:
l.append(line)
print l
Yields: 产量:
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]
To output integers, you might as well convert the strings to integers directly: 要输出整数,您还可以将字符串直接转换为整数:
l = []
tst = open('test.csv')
reader = csv.reader(tst)
for line in reader:
l.append([int(i) for i in line])
print l
Yields: 产量:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.