Python将文本文件中每行的最后一个数字放入列表中 [英] Python take the last number of each line in a text file and make it into a list

查看:693
本文介绍了Python将文本文件中每行的最后一个数字放入列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想每行的最后一个数字.

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")

我尝试使用line.pop()获取最后一个元素,但仅从一行开始获取它?如何从每一行中获取并将其存储在列表中?

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]

对于更复杂的csv文件,您可能需要查看标准库中的csv模块,因为它将正确处理字段引用等.

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.

这篇关于Python将文本文件中每行的最后一个数字放入列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆