s_b*_*man 5 python csv dictionary python-2.7
啊,我正在编写一个Python脚本来过滤一些大的CSV文件.
我只想保留符合我标准的行.
我的输入是以下格式的CSV文件
Run Code Online (Sandbox Code Playgroud)Locus Total_Depth Average_Depth_sample Depth_for_17 chr1:6484996 1030 1030 1030 chr1:6484997 14 14 14 chr1:6484998 0 0 0
我想返回Total_Depth为0的行.
我一直在听这个答案来读取数据.但我坚持试图解析行并拉出符合我条件的行.
这是我到目前为止的代码:
import csv
f = open("file path", 'rb')
reader = csv.reader(f) #reader object which iterates over a csv file(f)
headers = reader.next() #assign the first row to the headers variable
column = {} #list of columns
for h in headers: #for each header
column[h] = []
for row in reader: #for each row in the reader object
for h, v in zip(headers, row): #combine header names with row values (v) in a series of tuples
column[h].append(v) #append each value to the relevant column
Run Code Online (Sandbox Code Playgroud)
我知道我的数据现在是字典格式,我想根据"Total_Depth"键过滤它,但我不确定如何做到这一点.我的目标是使用'if'语句来选择相关的行,但不知道如何使用字典结构来执行此操作.
任何建议将不胜感激.SB :)
使用列表理解.
import csv
with open("filepath", 'rb') as f:
reader = csv.DictReader(f)
rows = [row for row in reader if row['Total_Depth'] != '0']
for row in rows:
print row
Run Code Online (Sandbox Code Playgroud)