python按行读取文件取消空白行_当使用python读取CSV文件时,如何跳过空行

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

由于您可能想要做的更复杂,而不是将非空白行打印到控制台(不需要使用CSV模块),以下是一个涉及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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值