I have a text file that is comma-separated with five different columns but I only want to get back the first column and the fourth column.
When I am using the split
function it is just splitting everything and I don't know how to get it so that it will just take the first column and then skip to the fourth column.
This is an example of the data I am trying to organise:
11.332,2,2,-465,0.928621379033569
What I would like to get back from this is 11.332
and -465
and forget about the rest of it
There are a few ways to do it.
Your question is tagged with csv
. You can parse CSV data with the csv
module:
import csv
with open('file.csv') as f:
for row in csv.reader(f):
print(row[0]) # the first field
print(row[3]) # the third field
For your sample data this would print:
11.332 -465
csv.reader()
is probably the best way to go, however, another method is to use tuple unpacking with _
to denote ignored fields:
line = '11.332,2,2,-465,0.928621379033569'
first, _, _, fourth, _ = line.split(',')
print(first)
print(fourth)
# 11.332
# -465
Of course there is nothing stopping you from binding all of the fields to variables, just replace _
with a meaningful variable name.
Alternatively you can split the whole line and then pluck out the fields that you want by subscripting:
line = '11.332,2,2,-465,0.928621379033569'
data = '11.332,2,2,-465,0.928621379033569'.split(',')
print(data[0])
print(data[3])
# 11.332
# -465
Or you could use operator.itemgetter
(combined with tuple unpacking):
from operator import itemgetter
fields = itemgetter(0, 3)
first, fourth = fields(line.split(','))
print first
print fourth
# 11.332
# -465
I managed to figure it out
for line in eda:
print (line.split(',')[0])
print (line.split(',')[3])
This is giving me out the two results that i need and forgetting about the rest of them
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.