你可能是也可能不是 aware的 ASCII 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/