简体   繁体   中英

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 in stockArray:
        List = line.pop()
        #print(line.pop())
        #print(', '.join(line))
else:
    print("Finished")

I tried using the line.pop() to take the last element but it only takes it from one line? How can I get it from each line and store it in list?

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.

my_list = []
with open(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 = []
with open(home + "/Documents/stocks/" + filePath , newline='') as f:
    for line in f:
        my_list.append(line.split(',')[-1]) # adds the last character to the list

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