Python csv跳过前两个空行 [英] Python csv skip first two empty rows
问题描述
在任何人将此标记为重复之前,我已经尝试过从isspace,startswith,itertools filterfunction,readlines()[2:]的一切。我有一个Python脚本,它搜索了数百个CSV文件,并从左边第八列中打印出匹配字符串(在这种情况下是一个唯一的ID)。
Before anyone marks this as duplicate, I have tried everything from isspace, startswith, itertools filterfunction, readlines()[2:]. I have a Python script that searches hundreds of CSV files and prints the row with the matching string (in this case a unique ID) in the eighth column from the left.
import csv
import glob
csvfiles = glob.glob('20??-??-??.csv')
for filename in csvfiles:
reader = csv.reader(open(csvfiles))
for row in reader:
col8 = str(row[8])
if col8 == '36862210':
print row
代码与测试.csv文件一起使用。但是,我正在使用的真正的.csv文件都有空白的前两行。我得到这个错误消息。
The code works with test .csv files. However, the real .csv files I'm working with all have blank first two rows. And I am getting this error message.
IndexError:列表索引超出范围
IndexError: list index out of range
这是我的最新代码:
import csv
import glob
csvfiles = glob.glob('20??-??-??.csv')
for filename in csvfiles:
reader = csv.reader(open(csvfiles))
for row in reader:
if not row:
continue
col8 = str(row[8])
if col8 == '36862210':
print row
推荐答案
尝试跳过前两行使用 code>代替:
Try to skip the first two row using next
instead:
import csv
import glob
csvfiles = glob.glob('20??-??-??.csv')
for filename in csvfiles:
reader = csv.reader(open(filename))
next(reader)
next(reader)
for row in reader:
col8 = str(row[8])
if col8 == '36862210':
print row
这篇关于Python csv跳过前两个空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!