从CSV文件中读取行数据

时间:2015-04-25 09:52:26

标签: python

我目前正在尝试创建一个读取CSV文件的程序,更具体地说是行数据(行间数据)

Sampledata.csv:

['Time', 'Date', 'Color  ', 'Name']
['1pm', '01-01-99', 'blue', 'jack']
['2pm', '02-02-99', 'green', 'kevin']
['3pm', '03-03-99', 'yellow', 'phil']
['4pm', '04-04-99', 'white', 'alice']
['5pm', '05-05-99', 'black', 'bob']

这是我的代码:

import csv  
with open('Sampledata.csv', 'r') as csvfile :
      regnumber = input("What is your regnumber?")
      reader = csv.reader(csvfile, delimiter=',')
for row in reader:
     print(row) # here lies the problem(python is reading columnal data (data going down) instead of row(lines across) data#

问题在于读取列(数据下降)。 Python会读取列。

输出:

Date
01-01-99
02-02-99
03-03-99
04-04-99
05-05-99

1 个答案:

答案 0 :(得分:1)

这是你正在寻找的吗?

import csv  #ignore my stupidity with the indentation and spaces#
with open('Sampledata.csv', 'r') as csvfile :
    regnumber = raw_input("Enter the time:")
    reader = csv.reader(csvfile)
    for row in reader:
        if(row[0]==regnumber):
            print ', '.join(row)
        else:
            continue

以上代码逐行打印来自csv文件的值。