为什么需要在此csv文件中添加引号? [英] Why do I need to add quotes to this csv File?

查看:292
本文介绍了为什么需要在此csv文件中添加引号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要解析的csv文件,运行程序时出现列表索引超出范围的错误。

I have a csv file I'm trying to parse, and I'm getting a list index out of range error when I run my program.

以下是原始的csv文件:

Here's the original csv file:

test.csv

Date, Time To Process
10/26/2017 7:57:28 PM, 5
10/26/2017 7:57:46 PM, 3
10/26/2017 7:57:47 PM, 1
10/26/2017 7:57:49 PM, 1
10/26/2017 7:57:50 PM, 6
10/26/2017 7:57:52 PM, 5

这是我的代码:

import csv

with open('test.csv', 'rb') as n:
    has_header = csv.Sniffer().has_header(n.read(1024))
    n.seek(0)
    reader = csv.reader(n)
    if has_header:
        next(reader)
    dates = []
    timeToProcess = []
    for row in reader:
        print row
        values = row[0].split(',')
        dates.append(values[0])
        timeToProcess(values[1])

此w生病只是打印csv文件的第一行,然后输出错误 timeToProcess.append(values [1])IndexError:列表索引超出范围

This will just print the first row of the csv file, and then output the error timeToProcess.append(values[1]) IndexError: list index out of range

如果我将csv文件更改为每行都加引号,则一切正常。为什么会这样,并且该程序有没有办法在csv文件中不带引号的情况下运行?

If I change the csv file to have quotes around each row, everything works as expected. Why is that, and is there a way for this program to run without the quotes in the csv file?

test.csv

Date, Time To Process
"10/26/2017 7:57:28 PM, 5"
"10/26/2017 7:57:46 PM, 3"
"10/26/2017 7:57:47 PM, 1"
"10/26/2017 7:57:49 PM, 1"
"10/26/2017 7:57:50 PM, 6"
"10/26/2017 7:57:52 PM, 5"


推荐答案

您正在使用 csv .reader 手动拆分行。没必要- csv 模块的工作是为您隔离单元格(即使它们包含诸如逗号或换行符之类的元字符)。

You're using csv.reader and manually splitting the rows. That's not necessary - the csv module's job is to isolate the "cells" for you (even if they contain metacharacters like commas or newlines). Just do

with open('test.csv', 'rb') as n:
    # ...  
    for row in reader:
        dates.append(row[0])
        timeToProcess(row[1]) # maybe better int(row[1])?

另外,请注意 PEP-8(Python代码样式指南)-每个缩进级别4个空格。

Also, please observe PEP-8 (Style Guide for Python code) - 4 spaces per indentation level.

这篇关于为什么需要在此csv文件中添加引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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