简体   繁体   中英

How to get the first value of last row of a CSV file using python

How can i get the values of the 'Number' field of last row of the csv file

Number, Product, Year
1,JK,2016,
2,TL,2016,
3,HNK,2016,

in this case the value 3 so that i can store the value of three to a variable.

You could load your csv file into a pandas DataFrame and read the last row from it:

import pandas as pd

df = pd.read_csv('path_to_file.csv')
last_number = df['Number'].values[-1]

if you want to use python only :

with open('csv_file.csv','r') as f:
    opened_file = f.readlines()
    var = opened_file[-1].split(',')[0]

Try this :

import pandas as pd
print(pd.read_csv("test1.csv").iloc[-1]["Number"])    # Prints 3

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM