如何将CSV文件的数据同时导入为字符串列表和整数列表?
到目前为止,我已经写好了代码,可以打开一个CSV文件,并把里面的数据导入到几个列表中。不过,这些列表现在都是字符串类型的,我需要一些是字符串列表,另一些则是整数列表。
目前我有以下代码来把数据导入到一系列列表中。
filename = open('/path/to/myfile.csv', 'r')
file = csv.DictReader(filename)
Sample_ID = []
Well = []
DNA_vol =[]
ddH2O_vol = []
for col in file:
Sample_ID.append(col['Sample_ID'])
Well.append(col['Well'])
DNA_vol.append(col['DNA_vol'])
ddH2O_vol.append(col['ddH2O_vol'])
列表的显示如下:
Well = ['A1', 'A2', 'A3', 'A4', 'A5']
DNA_vol = ['2', '4', '6', '8', '10', '1', '2', '4', '8', '10']
Sample_ID和Well的显示是正确的,都是字符串列表。但是我需要DNA_vol和ddH2O_vol是整数列表,这样我的代码才能正常工作。
我尝试在添加数据的部分和之后的地方加上int()函数,但都没有成功。
我该如何修改DNA_vol.append...和ddH2O_vol.append...这两行代码,让它们生成整数列表呢?
其他类似的问题是用
open with
来打开文件的,所以这些解决方案对我的具体情况没有帮助。
非常感谢!
5 个回答
0
首先,要确保 DNA_vol
和 ddH2O_vol
里的所有数值都是整数。如果不是,就要加一个“尝试-捕获”块来处理那些不是整数的情况。
filename = open('/path/to/myfile.csv', 'r')
file = csv.DictReader(filename)
Sample_ID = []
Well = []
DNA_vol =[]
ddH2O_vol = []
for col in file:
Sample_ID.append(col['Sample_ID'])
Well.append(col['Well'])
try:
DNA_vol.append(int(col['DNA_vol']))
except ValueError:
DNA_vol.append(0)
try:
ddH2O_vol.append(int(col['ddH2O_vol']))
except ValueError:
ddH2O_vol.append(0)
因为你没有提供 csv 文件的样本或其他额外信息,所以在这段代码中假设如果出现任何异常,值就会被设置为 0 [或者说,0 会被添加到列表中]
0
好的,这里有几点需要注意:
- 使用
with open(...) as f
的方式,跟f = open(...)
然后在代码块结束时关闭文件是一样的。 - 你没有关闭文件,所以要么在读完后手动关闭它,要么使用
with
语句来自动处理。 - 你正在读取一个纯文本文件,所以自然读取到的内容都是文本格式。关于
csv
的文档里也没有提到int
类型。所以你需要自己处理这个转换! - 变量名
col
可能会让人误解,因为你是逐行(或逐行)解析文件,这对 CSV 文件来说是一样的。
要把你的 DNA_vol
值变成 int
类型,只需要简单修改一行:
DNA_vol.append(int(col['DNA_vol']))
不过,如果我们不在这里提供信息和建议给未来的人,这就不是 StackOverflow 了。
import csv
import os
# Either use `with open(...) as ..:` here or close the file at the end
file_obj = open('/path/to/my/file.csv', 'r')
# Add a level of indentation to **ALL** below code if you're using a `with` block!
file = csv.DictReader(file_obj)
# Get your lists set up
sample_ID = []
well = []
DNA_vol = []
ddH2O = []
# Loop over the list of dicts
for row in file:
sample_ID.append(line['Sample_ID'])
well.append(line['Well'])
# Check if the other two fields are purely numeric values and, if so, parse them as ints.
# replace with `isdecimal` and `float` if the numbers might not be just ints
# Defaults to 0 for numeric values, but feel free to pick any other number
# if your dataset has a strict minimum or something
DNA_vol.append(if line['DNA_vol'].isdigit() int(line['DNA_vol']) else 0)
ddH2O.append(if line['ddH2O_vol'].isdigit() int(line['ddH2O_vol']) else 0)
# That's all there's to it! Now if you used a with block, you don't need the next line:
os.close(file_obj) # Don't leak the file descriptor
# When using the `open` builtin, and you're not passing a custom opener, `os.open` is the default