簡體   English   中英

Python csv跳過前兩個空行

[英]Python csv skip first two empty rows

在有人將此標記為重復之前,我已經嘗試過isspace,startswith,itertools filterfunction,readlines()[2:]的所有操作。 我有一個Python腳本,可以搜索數百個CSV文件,並在左側的第八列中顯示帶有匹配字符串(在本例中為唯一ID)的行。

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文件前兩行都為空白。 而且我收到此錯誤消息。

IndexError:列表索引超出范圍

這是我的最新代碼:

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

嘗試使用next跳過前兩行:

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

csv閱讀器采用iterable ,它可以是文件對象,但不一定是。

您可以創建一個生成器,從文件中刪除所有空白行,如下所示:

csvfile = open(filename)
filtered_csv = (line for line in csvfile if not line.isspace())

filtered_csv生成器將一次從文件對象中懶惰地拉一行,如果該行完全是空白,則跳到下一行。

您應該可以像下面這樣編寫代碼:

for filename in csvfiles:
    csvfile = open(filename)
    filtered_csv = (line for line in csvfile if not line.isspace())
    reader = csv.reader(filtered_csv)
    for row in reader:
        col8 = str(row[8])
        if col8 == '36862210':
            print row

假設非空白行的格式正確,即所有行都有第8個索引,則不應獲得IndexError

編輯 :如果您仍然遇到IndexError ,可能不是因為僅由空格組成的一行。 捕獲異常並查看行:

try:
    col8 = str(row[8])
    if col8 == '36862210':
        print row
except IndexError:
    pass

檢查實際導致錯誤的CSV閱讀器的輸出。 如果該行是不打印其內容的對象,請改為print list(row)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM