Python csv跳过前两个空行

编程入门 行业动态 更新时间:2024-10-25 03:22:25
本文介绍了Python csv跳过前两个空行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在任何人将此标记为重复之前,我已经尝试过从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跳过前两个空行

本文发布于:2023-05-25 10:56:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/226639.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:空行   跳过   两个   Python   csv

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!