2014-03-05 48 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()