python - 使用 csv 模块读取 ascii 分隔文本?

标签 python csv newline

你可能是也可能不是 awareASCII delimited text ,它具有使用非键盘字符分隔字段和行的优势。

写出来很简单:

import csv

with open('ascii_delim.adt', 'w') as f:
    writer = csv.writer(f, delimiter=chr(31), lineterminator=chr(30))
    writer.writerow(('Sir Lancelot of Camelot', 'To seek the Holy Grail', 'blue'))
    writer.writerow(('Sir Galahad of Camelot', 'I seek the Grail', 'blue... no yellow!'))

而且,果然,你把东西倒出来了。但是,在阅读时,lineterminator 什么都不做,如果我尝试这样做:

open('ascii_delim.adt', newline=chr(30))

它抛出一个 ValueError: illegal newline value:

那么如何读取我的 ASCII 分隔文件?我是否只能做 line.split(chr(30))

最佳答案

您可以通过有效地将文件中的行尾字符转换为换行符来实现 csv.reader 被硬编码以识别:

import csv

with open('ascii_delim.adt', 'w') as f:
    writer = csv.writer(f, delimiter=chr(31), lineterminator=chr(30))
    writer.writerow(('Sir Lancelot of Camelot', 'To seek the Holy Grail', 'blue'))
    writer.writerow(('Sir Galahad of Camelot', 'I seek the Grail', 'blue... no yellow!'))

def readlines(f, newline='\n'):
    while True:
        line = []
        while True:
            ch = f.read(1)
            if ch == '':  # end of file?
                return
            elif ch == newline:  # end of line?
                line.append('\n')
                break
            line.append(ch)
        yield ''.join(line)

with open('ascii_delim.adt', 'rb') as f:
    reader = csv.reader(readlines(f, newline=chr(30)), delimiter=chr(31))
    for row in reader:
        print row

输出:

['Sir Lancelot of Camelot', 'To seek the Holy Grail', 'blue']
['Sir Galahad of Camelot', 'I seek the Grail', 'blue... no yellow!']

关于python - 使用 csv 模块读取 ascii 分隔文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30224364/

相关文章:

java - 为什么我们需要使用静态 block 加载 chilkat lib

python - IPC QLocalSocket -> C,为什么我的连接失败?连接失败: [2] (no such file?!)

python - 将 Python 与 Kivy 结合使用

python - 元组列表转为 CSV

r - 创建持久的多行字符串

awk - 需要一种方法从记录中间剥离额外的 CRLF

c++ - 考虑到\r\n

python - 为什么 python3 不关心源文件中的非 ascii 字符?

javascript - 如何从 Bootstrap 的模态形式发布数据?

matlab - 用 MATLAB 读取 CSV 文件?