Skip to content Skip to sidebar Skip to footer

Python Take The Last Number Of Each Line In A Text File And Make It Into A List

I just want the last number of each line. with open(home + '/Documents/stocks/' + filePath , newline='') as f: stockArray = (line.split(',') for line in f.readlines()) for line

Solution 1:

You probably just want something like:

last_col = [line.split(',')[-1] for line in f]

For more complicated csv files, you might want to look into the csv module in the standard library as that will properly handle quoting of fields, etc.

Solution 2:

my_list = []
withopen(home + "/Documents/stocks/" + filePath , newline='') as f:
    for line in f:
        my_list.append(line[-1]) # adds the last character to the list

That should do it.

If you want to add the last element of a list from the file:

my_list = []
withopen(home + "/Documents/stocks/" + filePath , newline='') as f:
    for line in f:
        my_list.append(line.split(',')[-1]) # adds the last character to the list

Post a Comment for "Python Take The Last Number Of Each Line In A Text File And Make It Into A List"