在CSV解析时跳过空行 [英] Skip empty lines while CSV parsing

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

问题描述

我目前正在从网址中提取CSV文件并修改其中的条目。我目前使用StreamReader来读取CSV的每一行并将其拆分成一个数组,我可以根据其位置修改每个条目。

I'm currently working with pulling a CSV file from a URL and modifying it's entries. I'm currently using a StreamReader to read each line of the CSV and split it into an array, where I can modify each entry based on its position.

CSV是从电子表单提供者生成,其中特定表单条目是多行字段,其中用户可以添加多个笔记。

The CSV is generated from an e-form provider where a particular form entry is a Multi-Line field, where a user can add multiple notes. However, when a user enters a new note, they are separating each note by a line return.

CSV示例:

"FName","LName","Email","Note 1: some text

Note 2: some text"

由于我的代码是逐行拆分每个CSV条目,一旦它到达这些笔记,它认为它是一个新的CSV条目。这导致我的代码修改条目不工作,因为元素位置变得不正确。 (具有空行或单行注释字段的CSV条目工作正常)

Since my code is splitting each CSV entry by line, once it reaches these notes, it believes it to be a new CSV entry. This is causing my code that modifies the entries to not work since the element positions become incorrect. (CSV entries with empty or single line note fields work fine)

有关最佳方法的任何想法吗?我尝试添加代码来替换回车符或跳过空行,但它似乎不帮助。

Any ideas on the best approach to take for this? I've tried adding code to replace carriage returns or to skip empty lines but it doesn't seem to help.

推荐答案

一个合适的CSV库来处理写和解析。这里有几个边缘情况可以处理,不仅仅是新行。用户也可以在他们的笔记中插入逗号或引号,并且自己处理这些会很麻烦。

Use a proper CSV library to handle the writing and parsing. There's a few edge cases to handle here, not only the new line. Users could also insert commas or quotes in their notes and it will become very messy to handle this by yourself.

请尝试 uniVocity-parsers ,因为它可以处理各种情况下解析和写入CSV。

Try uniVocity-parsers as it can handle all sorts of situations when parsing and writing CSV.

披露:我是这个图书馆的作者。它是开源和免费的(Apache V2.0许可证)。

Disclosure: I am the author of this library. It's open-source and free (Apache V2.0 license).

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

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