使用csv模块来读取ascii分隔的文本? [英] Using csv module to read ascii delimited text?

查看:822
本文介绍了使用csv模块来读取ascii分隔的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以或不可以感知 ASCII分隔的文本

写这个很容易:

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 什么都不做,如果我尝试做:

And, sure enough, you get things dumped out properly. However, on reading, lineterminator does nothing, and if I try to do:

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

ValueError:illegal newline value:

那么如何读取我的ASCII分隔文件?我改用 line.split(chr(30))

So how can I read in my ASCII delimited file? Am I relegated to doing line.split(chr(30))?

推荐答案

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

You can do it by effectively translating the end-of-line characters in the file into the newline characters csv.reader is hardcoded to recognize:

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!']

这篇关于使用csv模块来读取ascii分隔的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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