[英]Error while reading csv file using python
I am trying to read a specific comma value from a csv file but i am getting the full row value how can i get the specific comma value 我正在尝试从csv文件中读取特定的逗号值,但是我正在获取完整的行值,我该如何获取特定的逗号值
My csv looks like this 我的csv看起来像这样
Index,Time,Energy
1,1.0,45.034
i need to get the values of Energy in each column. 我需要获取每列中的Energy值。
import csv
with open('somefile.csv') as f:
reader = csv.DictReader(f, delimiter=',')
rows = list(reader)
for row in rows:
print(row['Energy'])
f = open('file.txt')
f.readline() # To skip header
for line in f:
print(line.split(',')[2])
f.close()
If you want it working even if the position of column Energy changes, you can do this: 如果即使“能量”列的位置发生变化也希望它起作用,则可以执行以下操作:
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
Check the below code. 检查以下代码。 Hoping this is what you are looking for.
希望这就是您想要的。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.