使用python读取csv文件时出错

时间:2014-03-05 08:45:34

标签: python csv

我正在尝试从csv文件中读取特定的逗号值但是我得到完整的行值我如何获得特定的逗号值

我的csv看起来像这样

Index,Time,Energy
1,1.0,45.034

我需要在每列中获取能量值。

4 个答案:

答案 0 :(得分:0)

import csv

with open('somefile.csv') as f:
  reader = csv.DictReader(f, delimiter=',')
  rows = list(reader)

for row in rows:
   print(row['Energy'])

答案 1 :(得分:0)

f = open('file.txt')
f.readline() # To skip header
for line in f:
    print(line.split(',')[2])
f.close()

答案 2 :(得分:0)

如果您希望它能够工作,即使列能量的位置发生变化,您也可以这样做:

with open('your_file.csv') as f:
    # Get header
    header = f.readline()
    energy_index = header.index('Energy')
    # Get Energy value
    for line in f.readlines():
        energy = line.split(',')[energy_index]
        # do whatever you want to do with Energy

答案 3 :(得分:0)

检查以下代码。希望这是你正在寻找的。

import csv
try:
    fobj = open(file_name, 'r')
    file_content = csv.reader(fobj, delimiter=',', quotechar='|')
except:
    fobj.close()
    file_content = False

if file_content:
    for row_data in file_content:
        try:
            # This will return the 3rd columns value i.e 'energy'
            row_data[2] = row_data[2].strip()
            print row_data[2]
        except:
            pass

    fobj.close()