栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在使用python读取CSV文件时跳过空白行

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在使用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__.pyimport csv as _csv# Real comments are more complicated ...def is_comment(line):    return line.startswith('#')# Kind of sily wrapperdef 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 Mbdef 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 RAMdef 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 withdef 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:UsersBKA4ABTDesktopTest_SpecificationRDBI.csv"    main_v1(csv_path)    print('n'*3)    main_v2(csv_path)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/651488.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号