2014-03-05 47 views
0

我想从一个CSV文件中读取特定逗号值,但我得到了全行值我怎样才能得到具体的逗号值读取csv文件错误而使用python

我的CSV看起来像这样

Index,Time,Energy 
1,1.0,45.034 

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

+1

你能告诉我们一些代码吗? – Bach

+0

plz粘贴您的代码,您当前的输出或返回值,以及您在此处的预期输出。 – zhangxaochen

回答

0
import csv 

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

for row in rows: 
    print(row['Energy']) 
0
f = open('file.txt') 
f.readline() # To skip header 
for line in f: 
    print(line.split(',')[2]) 
f.close() 
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 
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()