Reputation: 117
How would I go about printing out the last value after comma in a csv file, i want to loop through the file and print out the last values:
Data:
20181016135716, 00-00-00-00-00-04, 10.0.0.1, 10.0.0.8, 6, 3, 198, 3, 155000000, 3, 198, 3, 155000000, 62.757528
20181016135716, 00-00-00-00-00-04, 10.0.0.8, 10.0.0.1, 6, 2, 132, 3, 123000000, 2, 132, 3, 123000000, 42.267051
Code:
import csv
with open('output.csv', 'r') as f:
for row in (list(csv.reader(f))):
print(', '.join(row)[-1])
This only give me the last character 8 and 1
Upvotes: 1
Views: 1412
Reputation: 440
Every answer before answered the question. However, when your csv file will become larger, that way will not be most efficient one. I suggest to use pandas to do it, it is meant for that:
import pandas as pd
file = pd.read_csv('output.csv', header=None)
print(file.iloc[:, -1])
Output will be:
0 62.757528
1 42.267051
EDIT
To answer the comment, I made a benchmark with this code:
import pandas as pd
import csv
import timeit
def without_pandas():
with open('output.csv', 'r') as f:
for row in csv.reader(f):
value = float(row[-1])
def with_pandas():
file = pd.read_csv('output.csv', header=None)
for row in file.iloc[:, -1]:
value = float(row)
if __name__ == '__main__':
num = 10000
print("Without pandas:", timeit.timeit(
'without_pandas()', number=num,
setup="from __main__ import without_pandas")/num)
print("With pandas:", timeit.timeit(
'with_pandas()', number=num,
setup="from __main__ import with_pandas")/num)
The output is:
Without pandas: 0.012996618213300826
With pandas: 0.012586948527599453
with a file of exactly 751K (6864 lines), when indeed the efficiency is quite the same for smaller file.
Upvotes: -1
Reputation: 1905
This is because you are joining the list first and then retrieve the last item of that string, which happens to be the last character. Try parsing it like this instead:
import csv
with open('output.csv', 'r') as f:
for row in csv.reader(f):
value = float(row[-1])
print(value)
Upvotes: 1
Reputation: 343
use this:
import csv
with open('output.csv', 'r') as f:
for row in (list(csv.reader(f))):
print(', '.join(row.split(',')[-1])
Basically you are just accessing the last character of the row. But you need to split it with , and then pick the last value
Upvotes: 2