[英]Python csv.reader when line is encapsulated by strings
我正在尝试读取一个csv文件。
with open(os.path.join(folder,mfile),'r') as csvfile:
fileReads = csv.reader(csvfile, delimiter=',')
for i, line in enumerate(fileReads):
print 'line[{}] = {}'.format(i, line)
不幸的是,我的数据以以下格式包含在CSV文件中:
"val1, val2, val3"
(包括引号,不要问为什么会这样...)
这导致csv.reader将整行作为一个值返回-因此向控制台的输出类似于
line[1] = ['val1,val2,val3']
不出所料。
将文件包装在生成器函数中以去除引号:
def strip_quotes(iterable):
for line in iterable:
yield line.rstrip('\n').strip('"') + '\n'
然后使用如下功能:
fileReads = csv.reader(strip_quotes(csvfile), delimiter=',')
csv.reader()
类愉快地接受任何可迭代的对象,而不仅仅是文件。
可以调整strip_quotes()
函数以适合您的特定文件内容。 例如,如果列周围也有引号,则可以仅从行的开头和结尾删除一个引号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.