我有一个由'|'分隔的CSV。我正在尝试读取CSV,按第8列排序,并将排序后的数据作为标准CSV输出到stdout。问题是输入CSV中的某些行没有8列。可以完全跳过那些没有列8的行。现在当它遇到没有第8列的行时,它会抛出错误“列表索引超出范围”。如果我能让它继续并忽略那一行它将是完美的。
任何帮助将不胜感激。当然愿意完全改变代码块。
with open(sys.argv[1]) as openFile:
reader = csv.reader((x.replace('\0','') for x in openFile), delimiter='|')
col = 8
sortedReader = sorted(reader, key=lambda k: (k[col] is None, k[col] == "", k[col]), reverse=True) # This was my attempted solution found on Google/StackOverflow. Does not work.
csvout = csv.writer(sys.stdout, delimiter=',')
for row in sortedReader:
try:
csvout.writerow(row)
except:
sys.stderr.write('[!] Error in row')
sys.stderr.write(row)
continue
答案 0 :(得分:1)
只需在排序前过滤行
$args = array(
'post_type' => 'knowledgebase',
'tax_query' => array(
array(
'taxonomy' => 'knowledgebase-categories',
'field' => 'slug',
'terms' => 'knowledgebase-terms',
),
),
);
$query = new WP_Query( $args );