Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python csv字段中的新行字符_Python_Csv - Fatal编程技术网

Python csv字段中的新行字符

Python csv字段中的新行字符,python,csv,Python,Csv,我在读取以thorn分隔的csv文件时遇到问题,我认为该文件的一个字段中有一个新行字符。它迫使行超过两行,因此我无法读取行的最后字段中的值。我曾尝试过以新行模式打开,但不确定最好的方法是什么 这就是我试图在python中读取文件的方式: csv.register_dialect('BB', delimiter='\xfe') with open(file, 'rU') as file_in: log=csv.reader(file_in, dialect='BB') for r

我在读取以thorn分隔的csv文件时遇到问题,我认为该文件的一个字段中有一个新行字符。它迫使行超过两行,因此我无法读取行的最后字段中的值。我曾尝试过以
新行模式打开,但不确定最好的方法是什么

这就是我试图在
python
中读取文件的方式:

csv.register_dialect('BB', delimiter='\xfe')
with open(file, 'rU') as file_in: 
    log=csv.reader(file_in, dialect='BB')
    for row in log:
        print row
这对大多数文件都很有效,但我假设有一行在其中一个字段中有一个新行字符-我不确定如何最好地诊断它。这是记事本中该行的屏幕截图,您可以看到,当该行看起来像下面的两行时,它将该行强制为两行。

使用
csv.reader阅读此文件
行如下所示:

['06-13-2015-10:13:41','0','0','142','5','7.0','2','cmhkl966','amex_674','1','0.00','


i、 e.在第一个撇号处被截断。

我将您的问题简化了一点(希望我抓住了问题的原因):

输出:

['a', 'b', 'hello\nworld']

更新:

根据注释中的要求:这里是从文件中读取
.csv
的版本。
test.csv
的内容包括:

aþbþ'hello
world'þc
dþeþ'hello
other
things'þf
gþhþiþj
以及python代码:

import csv
from pathlib import Path

HERE = Path(__file__).parent
DATA_PATH = HERE / '../data/test.csv'

with DATA_PATH.open('rU') as file_in:
    log=csv.reader(file_in, delimiter='\xfe', quotechar="'")
    for row in log:
        print(row)
哪些产出:

['a', 'b', 'hello\nworld', 'c']
['d', 'e', 'hello\nother\nthings', 'f']
['g', 'h', 'i', 'j']

您也可以检查下一行的第一个元素是否以时间戳开头,如果不是,则在打印前使用list
extend
函数将其添加到当前行的内容中

免责声明:未经测试

import re

csv.register_dialect('BB', delimiter='\xfe')
with open(file, 'rU') as file_in: 
    log=csv.reader(file_in, dialect='BB')
    for i in range(0, len(log) - 1):
        if re.search('\d+-\d+-\d+-\d+:\d+:\d+', log[i+1][0]) is None:
            i.extend(log[i+1])
        print i

当你从文件中读取数据时,你能不能也演示一下同样的方法,而不是StringIO?谢谢你指出这里可能会出错。更新了。谢谢,这很有效。我认为解决方案可能涉及引用,但我不确定应该如何处理。如果您要在afield中使用新行编写csv,您将如何解决该问题?@romainjouin没有尝试过,但颠倒上述过程(从列表开始并编写它们)应该是可行的。不是吗?这不是我第一次把
þ
作为csv分隔符。这有什么原因吗?有没有默认使用此分隔符的应用程序?谢谢-我同意,我认为这也可以解决此问题,但我接受hiro的回答,因为这意味着成本增加更少
import re

csv.register_dialect('BB', delimiter='\xfe')
with open(file, 'rU') as file_in: 
    log=csv.reader(file_in, dialect='BB')
    for i in range(0, len(log) - 1):
        if re.search('\d+-\d+-\d+-\d+:\d+:\d+', log[i+1][0]) is None:
            i.extend(log[i+1])
        print i