如何在使用python读取CSV文件时跳过空行 [英] how to skip blank line while reading CSV file using python

查看:4793
本文介绍了如何在使用python读取CSV文件时跳过空行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码,我可以打印每行,但当空白行出现它打印;因为CSV文件格式,所以我想跳过,当空行出现

This is my code i am able to print each line but when blank line appears it prints ; because of CSV file format, so i want to skip when blank line appears

import csv
import time

ifile = open ("C:\Users\BKA4ABT\Desktop\Test_Specification\RDBI.csv", "rb")
for line in csv.reader(ifile): 
    if not line: 
        empty_lines += 1 
        continue
    print line


推荐答案

如果你想跳过所有的空格行,你应该使用这个测试:''.isspace()

If you want to skip all whitespace lines, you should use this test: ' '.isspace().

由于您可能想要做一些比将空白行打印到控制台更复杂的事情(无需使用CSV模块),下面是一个示例包含一个DictReader:

Since you may want to do something more complicated than just printing the non-blank lines to the console(no need to use CSV module for that), here is an example that involves a DictReader:

#!/usr/bin/env python
# Tested with Python 2.7

# I prefer this style of importing - hides the csv module
# in case you do from this_file.py import * inside of __init__.py
import csv as _csv


# Real comments are more complicated ...
def is_comment(line):
    return line.startswith('#')


# Kind of sily wrapper
def is_whitespace(line):
    return line.isspace()


def iter_filtered(in_file, *filters):
    for line in in_file:
        if not any(fltr(line) for fltr in filters):
            yield line


# A dis-advantage of this approach is that it requires storing rows in RAM
# However, the largest CSV files I worked with were all under 100 Mb
def read_and_filter_csv(csv_path, *filters):
    with open(csv_path, 'rb') as fin:
        iter_clean_lines = iter_filtered(fin, *filters)
        reader = _csv.DictReader(iter_clean_lines, delimiter=';')
        return [row for row in reader]


# Stores all processed lines in RAM
def main_v1(csv_path):
    for row in read_and_filter_csv(csv_path, is_comment, is_whitespace):
        print(row)  # Or do something else with it


# Simpler, less refactored version, does not use with
def main_v2(csv_path):
    try:
        fin = open(csv_path, 'rb')
        reader = _csv.DictReader((line for line in fin if not
                                  line.startswith('#') and not line.isspace()),
                                  delimiter=';')
        for row in reader:
            print(row)  # Or do something else with it
    finally:
        fin.close()


if __name__ == '__main__':
    csv_path = "C:\Users\BKA4ABT\Desktop\Test_Specification\RDBI.csv"
    main_v1(csv_path)
    print('\n'*3)
    main_v2(csv_path)

这篇关于如何在使用python读取CSV文件时跳过空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆