Python CSV:读取以逗号终止的行将导致结果为空 [英] Python CSV: reading rows terminated by comma results in an empty result

查看:81
本文介绍了Python CSV:读取以逗号终止的行将导致结果为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果这是一个愚蠢的问题,请随意骚扰我,因为我自己找不到正确的答案.我正在尝试读取CSV格式的文件,该文件的每一行都包含数据,并且每一行都以逗号结尾.像这样:

If this is a stupid question, please feel free to harass me for not finding the correct answer on my own. I'm trying to read a CSV-formatted file that contains data on each row, and each row is terminated by a comma. Like this:

-1,
-1,
1,
1,

当我尝试使用Python的CSV函数时,我使用以下代码:

When I try to use Python's CSV-function, I use this code:

with open(waveform, 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
        print row

输出以下内容:

['-1', '']
['-1', '']
['1', '']
['1', '']

我希望它忽略每行上的空字符.你有什么建议吗?

I want it to ignore the empty char on each row. Do you have any advice?

推荐答案

忽略每行中的最后一个元素:

Ignore the last element in each line:

with open(waveform, 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
        print row[:-1]

或将每一行转换成字典:

or convert each line into a dict:

columns = ['value']
with open(waveform, 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
        rec = dict(zip(columns, row))
        print rec

打印

{'value': '-1'}
{'value': '-1'}
{'value': '1'}
{'value': '1'}

这篇关于Python CSV:读取以逗号终止的行将导致结果为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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