我只想要每行的最后一个数字。
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()来获取最后一个元素,但它只从一行获取它?如何从每一行获取并将其存储在列表中?
答案 0 :(得分:6)
你可能只想要这样的东西:
last_col = [line.split(',')[-1] for line in f]
对于更复杂的csv文件,您可能需要查看标准库中的csv
模块,因为它将正确处理字段引用等。
答案 1 :(得分:0)
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
应该这样做。
如果要从文件中添加列表的最后一个元素:
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